7

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?

4

2 回答 2

8

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

模板是:

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

数据是:

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

当模板位于隐藏的 div 中,然后再次位于脚本块中时,请参阅小提琴http://jsfiddle.net/KPasF/以获得不同的结果。

解释

当你把它放在一个 hidden<div>中时,浏览器会去除标签之外的内容<th>(the{{#numbers}}{{#numbers}}mustache 标签)。只剩下{{.}}, 它将绑定到 json 对象并呈现为[object Object]

将模板放入一个<script type='text/html'>块中,正如您所期望<th>的那样,我们得到了三个

如果将模板放在 a<div>而不是 a内,浏览器如何破坏模板的示例<script>

在此处输入图像描述

于 2013-03-15T12:21:36.173 回答
1

另一个示例,如果您有以下内联模板(包装在 div 中):

<div id="template">
   {#Users}
       <a href="/ViewUser?ID={UserID}">{UserName}</a>
   {/Users}
</div>

然后你使用 jQuery.html() 来抓取模板文本,你会得到不同的结果,具体取决于浏览器。Firefox 是最受破坏的,因为它避开了 href 中的括号。

铬 26.0.1410.64:

{#Users}
     <a href="/ViewUser?ID={UserID}">{UserName}</a>
{/Users}

火狐 10.0.1:

{#Users} 
    <a href="/ViewUser?ID=%7BUserID%7D">{UserName}</a> 
{/Users}

即 8.0.7601.17514:

{#Users} 
    <A href="/ViewUser?ID={UserID}">{UserName}</A> 
{/Users}
于 2013-04-17T13:05:04.770 回答