简体   繁体   English

我应该使用jQuery模板吗?

[英]Should I use jQuery Templates?

I have a page where search results are loaded from an XHR response. 我有一个页面,其中从XHR响应加载搜索结果。 What are the advantages of using jQuery templates to display search results in this situation, rather than using a more conventional approach with .html() or .load()? 在这种情况下,使用jQuery模板显示搜索结果有什么好处,而不是使用.html()或.load()的更常规方法?

Using templates allow you to keep a lot of escaped markup outside of Javascript code. 使用模板可让您在Javascript代码之外保留许多转义的标记。 Most Javascript solutions now use the technique (first documented, as far as I know, by John Resig ): you put the template markup inside a script tag with a type attribute set to text/html (or some other content-type unrecognized by the browser text/tmpl , text/jstmpl , whatever). 现在,大多数Javascript解决方案都使用该技术(据我所知,最早由John Resig记录 ):您将模板标记放入一个script标记中,其type属性设置为text/html (或其他一些无法识别的内容类型)浏览器text/tmpltext/jstmpl等)。

As for the specific choice of jQuery templating , this is a matter of some discussion. 至于jQuery模板的具体选择,这是一些讨论的问题。 For a while it looked like that code was going to become a part of the core jQuery code, but apparently that's off the agenda. 一段时间以来,该代码似乎将成为jQuery核心代码的一部分,但显然这不在议程之列。

(There are many alternative templating libraries, though -- personally I like Mustache because it's been ported to many languages besides Javascript, which I find useful.) (不过,还有许多其他的模板库-我个人很喜欢Mustache,因为除了Javascript(我认为它很有用)之外,它还已移植到许多语言。)

The main advantages are: 主要优点是:

  • Using a template engine makes it easy to separate out what's being displayed from how it's being displayed. 使用模板引擎可以轻松地将显示的内容与显示的内容分开。
  • You can reuse templates, if you need them in different scenarios 如果在不同情况下需要模板,则可以重复使用模板

The main disadvantage of a javascript templating engine is the overhead of execution, but it's only a problem if your template is big. javascript模板引擎的主要缺点是执行开销,但是如果模板很大,这只是一个问题。

Hope this helps. 希望这可以帮助。 Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM