How to apply jquery mustache to external file/template
I am using this to 'get' my external html file, and then use mustache to append to that template's id:
$.get('block.html', function(data) {
$('#mydiv').append(data);
var list = {
name : 'whatever'
};
$('#Block').mustache(list).appendTo('#mydiv');
开发者_StackOverflow社区 });
The file block.html
would look like:
<script id="Block" type="x-tmpl-mustache">
My name is {{name}}
</script>
Is there a better way of doing this? Because, at the moment, I am appending twice.
Well, the jquery mustache plugin is great for when the template is inside your current document.
But here you have a different use case and the helpers provided by mustache itself are sufficient to do the job. So, just :
$.get('block.html', function(template) {
var view = {name:'whatever'};
var html = Mustache.to_html(template, view);
// and now append the html anywhere you like
});
And in this case, your block.html can become:
My name is {{name}}
You can use a library that I wrote, Chevron, to load external templates from files like so:
You add in your HTML 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
精彩评论