为什么我们应该在脚本块中包装我们的模板? [英] Why should we wrap our templates inside script blocks?

查看:113
本文介绍了为什么我们应该在脚本块中包装我们的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所有JS模板引擎都建议将模板文本放在脚本块内,如下所示:

 < script id =peopleTemplatetype =text / template> 
{#人物}
< div class =person>名称:{firstName} {lastName}< / div>
{/ people}
< / script>

但许多开发人员(可以理解)不喜欢这种方式,因为他们在代码编辑器中丢失了HTML语法突出显示块。我已经看到了这样的解决方法:保持正确的HTML语法突出显示在< script> " text / html的"模板。这个问题并没有提出解决方法。



我知道一个危险是Web浏览器会尝试修复无效的HTML,因此调用$('#peopleTemplate')。html()将会有不可预知的结果。然而,在我的头顶,我想不出任何例子来说明这一点。

问题



用div替换脚本标记有哪些其他危险?

奖励:有人能拿出一个很好的小提示来说明浏览器的HTML自动修复功能吗?

解决方案

以下是浏览器自动修复问题的示例: http://jsfiddle.net/ KPasF /



模板为:

 < ;表> 
< tr>
{{#numbers}}< th> {{。}}< / th> {{/ numbers}}
< / tr>
< / table>

数据为:

  var json = {numbers:[1,2,3]}; 

查看小提琴 http://jsfiddle.net/KPasF/ 当模板处于隐藏div时,然后再次处于脚本块中时,获得不同结果。



解释



当你把它放在隐藏的< div> 时,浏览器将剥离< th> 标签( {{#numbers}} 之外的内容并且 {{#numbers}} 胡子标签)。它只是保留了 {{。}} ,它将绑定到json对象并呈现为 [object Object]

将模板放在< script type ='text / html'> 期望的是,我们得到了三个< th>



< div> 而不是< script>


Background

All the JS template engines recommend putting your template text inside script blocks like so:

<script id="peopleTemplate" type="text/template">
   {#people}
   <div class="person">Name: {firstName} {lastName}</div>
   {/people}
</script>

but many developers (understandably) dislike this because they lose HTML syntax highlighting in their code editor inside the script block. I've seen the workarounds like this: Keep correct HTML syntax highlighting in <script> "text/html" templates . This question is not asking about workarounds.

I know one danger is that web browsers will attempt to fix invalid HTML so calling $('#peopleTemplate').html() will have unpredictable results. However, off the top of my head, I cannot think of any examples to illustrate this.

Question

What are some of the other dangers of replacing the script tag with a div ?

Bonus: can someone come up with a good fiddle that illustrates the browser HTML auto-fixing?

解决方案

Here's an example of the browser auto-fixing issue: http://jsfiddle.net/KPasF/

The template is:

<table>
    <tr>
        {{#numbers}} <th> {{.}} </th> {{/numbers}}
    </tr>
</table>

The data is:

var json = { "numbers": [ 1, 2, 3 ] };

See the fiddle http://jsfiddle.net/KPasF/ for the different results when the template is in a hidden div, and then again in a script block.

Explanation

When you put this in a hidden <div>, the browser will strip the content outside the <th> tags (the {{#numbers}} and {{#numbers}} mustache tags). Which just leaves the {{.}}, which will bind to the json object and render as [object Object]

Putting the template in a <script type='text/html'> block works as you would expect, we get three <th>'s

Example of how browser mangles a template if housed inside a <div> instead of a <script>:

这篇关于为什么我们应该在脚本块中包装我们的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆