Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache, using external templates

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?

like image 716
pethel Avatar asked Jun 23 '12 09:06

pethel


3 Answers

There are several approaches to doing this.

  1. If you are using a server side scripting language like PHP, just include them in a seperate .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.
  2. The other approach is to load external HTML files with any of jQuery's $.get, $.getJSON, etc. methods. A more detailed implementation of this is given here.
like image 115
2 revs, 2 users 89% Avatar answered Oct 22 '22 07:10

2 revs, 2 users 89%


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));
like image 1
sansSpoon Avatar answered Oct 22 '22 08:10

sansSpoon


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

like image 1
Nicu Surdu Avatar answered Oct 22 '22 09:10

Nicu Surdu