简体   繁体   中英

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?

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 .

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM