I am reading about templating with Mustache.js. What i don't understand is how is where to put the templates. I don't wont them in the same file.
$.get('test.htm', function(templates) {
// Fetch the <script /> block from the loaded external
// template file which contains our greetings template.
var template = $(templates).filter('#tpl-greeting').html();
$('body').append(Mustache.render(template, templateData));
});
//test.htm
<script id="tpl-greeting" type="text/html">
<dl>
<dt>Name</dt>
<dd>{{name}}</dd>
<dt>Time</dt>
<dd>{{timeNow}}</dd>
</dl>
</script>
Do I have to create a controller that returns my template or can i reference it?
There are several approaches to doing this.
.mst
(the extension could be anything you want actually) file within the JS. For example,
var _templateName = <?= JS::mustache('content/templateName.mst') ?>;
. Thus, when the JS is actually rendered, it will be rendered with the markup but the code will still be maintainable. Besides, with this approach, if you're using an CDNs, your site will benefit greatly with the cached JS.$.get
, $.getJSON
, etc. methods. A more detailed implementation of this is given here.A 2018 alternative using fetch instead of jQuery:
fetch('template.mst')
.then(response => response.text())
.then(template => {
Mustache.parse(template);
var output = Mustache.render(template, data);
return document.getElementById('target').innerHTML = output;
}).catch(error => console.log('Unable to get the template: ', error.message));
You may put templates in separate files like you do with CSS and JS. You can use Chevron to load external templates from files like so:
You add in you template a link to your template file:
<link href="path/to/template.mustache" rel="template" id="templateName"/>
Then, in you JS you can render your template like so:
$("#templateName").Chevron("render", {name: "Slim Shady"}, function(result){
// do something with 'result'
// 'result' will contain the result of rendering the template
// (in this case 'result' will contain: My name is Slim Shady)
});
The docs of Chevron will give more examples
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