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 :
Storing in javascript variables : Hackish multiline strings, lots of escaping of quotes.
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 ?
HTML <template> Tag 1 Definition and Usage. The <template> tag is used as a container to hold some HTML content hidden from the user when the page loads. 2 Browser Support 3 Global Attributes. The <template> tag supports the Global Attributes in HTML. 4 More Examples. Fill the web page with one new div element for each item in an array.
Most HTML templates come in a zipped file. Go to the folder where your template has just been downloaded and extract it. Find ‘index.html’ or ‘index.htm’. In our example, index.html file is in Noah-master directory after extracting the zip file. Now open the file in any browser, for instance- Google Chrome.
To do this without the <template> tag, you have to create the HTML code with JavaScript to prevent the browser from rendering the code. The <template> tag supports the Global Attributes in HTML.
Content inside a <template> tag will not be rendered. The content can be made visible and rendered later by using JavaScript. Use the <template> tag when you have HTML code you want to use over and over again, but not until you ask for it.
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);
I'd use HTML "template" tag.
<template id="tmp">Some HTML here</template>
See this example:
https://jsfiddle.net/cityremade/xwLht8vc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With