Why should we wrap our templates inside script blocks?

dust.js, handlebars.js, jquery-templates, mustache, template-engine

Solution

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

Problem

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?

Original source

Related problems