Why should we wrap our templates inside script blocks?

只愿长相守 提交于 2019-12-05 05:01:21
Ross McNab

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>:

Another example, if you have the following inline template (wrapped in a div):

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

And then you use jQuery.html() to grab the template text, you will get different results depending on the browser. Firefox is the most mangled as it escapes the brackets inside the href.

Chrome 26.0.1410.64:

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

Firefox 10.0.1:

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

IE 8.0.7601.17514:

{#Users} 
    <A href="/ViewUser?ID={UserID}">{UserName}</A> 
{/Users}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!