Mustache using external patterns.

I read about templates with Mustache.js. I do not understand how to place the templates. I will not 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>

Should I create a controller that returns my template, or can I reference it?

+5
source share
3 answers

There are several ways to do this.

  • , PHP, .mst ( , ) JS. , var _templateName = <?= JS::mustache('content/templateName.mst') ?>;. , JS , , - . , , CDN, JS.
  • HTML jQuery $.get, $.getJSON .. .
+6

, CSS JS. Chevron , :

:

<link href="path/to/template.mustache" rel="template" id="templateName"/>

JS :

$("#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)
});

Chevron

+1

Alternative 2018 using sampling 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));
0
source

All Articles