12

I have some small template strings, which will be rendered through Mustache.js on the same page.I need not create seperate html files for templates.

Options for storing the templates :

  1. Storing in javascript variables : Hackish multiline strings, lots of escaping of quotes.

  2. Storing as innerHTML of hidden divs.

I tried method#2, but it does not seem to work correctly.

Fiddle: http://jsfiddle.net/RHwnq/2/

<html>
<head></head>
<body>
<div id='templates' class='hide' align="">
         <div id='tableTemplate'>
            <table class="table">
                 {{#name_list}}
                  <tr><td> {{name}} </td></tr>
                {{/name_list}}
            </table>
         </div>
</div>

<script>
 var template = $('#tableTemplate').html();
 console.log(template);
</script>

</body>
</html>

This logs :

{{#name_list}}
  {{name}} 
{{/name_list}}
<table class="table"><tbody><tr><td></td></tr></tbody></table>

Instead of :

  <table class="table">
                     {{#name_list}}
                      <tr><td> {{name}} </td></tr>
                    {{/name_list}}
  </table>

This might be to due to some markup correction by the browser. What are other good tricks to store HTML templates within an HTML page ?

DhruvPathak
  • 38,316
  • 14
  • 103
  • 164
  • What about not storing them in the same file, but loading them via AJAX? – feeela Nov 28 '12 at 11:37
  • @feeela no, I do not want to make ajax calls to load 2-3 small strings,I intend to store them in the same page. – DhruvPathak Nov 28 '12 at 11:38
  • In some tutorials related to backbone.js/underscore.js they stored the templates within tags. Take a closer look at this question: http://stackoverflow.com/questions/4912586/explanation-of-script-type-text-template-script – Marc Nov 28 '12 at 11:45

4 Answers4

27

I store them in a script tag, so they don't get rendered, like this:

<script id="abc-template" type="text/html">
    <h1>{{name}}</h1>
</script>

You can then reference them like this:

var template = $('#abc-template').html();
var html = Mustache.to_html(template, data);
$('#abc-div').html(html);
Ross McNab
  • 10,509
  • 3
  • 33
  • 32
6

Using <script> tags works great for this:

<script id="tableTemplate" type="text/html">
  <table class="table">
    {{#name_list}}
    <tr><td> {{name}} </td></tr>
    {{/name_list}}
  </table>
</script>

It's actually a drop-in replacement, it will work with your var template = $('#tableTemplate').html();

Andrea Campi
  • 436
  • 2
  • 10
1

Depending on your IDE, you may or may not get HTML syntax highlighting within <script></script> blocks. I use a div block as you did, but add

#templates {display: none;}

to the CSS.

abalter
  • 7,589
  • 12
  • 75
  • 118
1

I'd use HTML "template" tag.

<template id="tmp">Some HTML here</template>

See this example:

https://jsfiddle.net/cityremade/xwLht8vc/

cityremade
  • 21
  • 2