Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we wrap our templates inside script blocks?

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?

like image 717
Walter Stabosz Avatar asked Mar 13 '13 13:03

Walter Stabosz


2 Answers

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

enter image description here

like image 119
Ross McNab Avatar answered Nov 12 '22 00:11

Ross McNab


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}
like image 39
Walter Stabosz Avatar answered Nov 12 '22 01:11

Walter Stabosz