作者:zccst
jquery.mustache是用jQuery做了一层封装,提供了以下几个方法,让模板使用更便捷。
1,添加模板,使用异步的方式
var viewData = { name: 'Jonny' };
$.Mustache.load('./templates/greetings.htm')
.done(function () {
$('body').mustache('simple-hello', viewData);
});
// 详见下面 ./templates/greetings.htm源码
2,添加模板的其他几种方式。add, addFromDom
//直接行内添加
$.Mustache.add('string-template', '<p>Hi, {{name}}, this is an inline template<p>');
// These two are identical(相同的), the latter just provides a terser(简洁的) syntax.
$.Mustache.add('dom-template', $('#dom-template').html());
$.Mustache.addFromDom('dom-template');//包括从外界读取
$('#target').mustache('string-template', viewData, { method: 'prepend' });
3,The mustache selector also allows you to pass an Array of View Models to render which makes populating lists a breeze:
// Clear #someList and then render all the viewModels using the list-template.
var viewModels = [
{ name: 'Jonny' },
{ name: 'nock' },
{ name: 'lucy' }
];//注意是数组。
$('#target').empty().mustache('string-template', viewModels);
4,支持partials
$.Mustache.load('./templates/templates.htm')
.done(function () {
// Renders the `webcontent` template and the `footer-fragment` template to the page.
$('body').mustache('webcontent', { year: 2012, adjective: 'EPIC' });
});
// 详见下面 ./templates/templates.htm源码
5,templates(), add(), clear()其他方法
console.log($.Mustache.templates());//查看已add的所有模板
console.log($.Mustache.has('string-template'));//查询某一个模板是否存在
$.Mustache.clear(); //清除所有已add的模板,变空了
console.log($.Mustache.templates());//经测试,已经空了
./templates/greetings.htm源码
<script id="simple-hello" type="text/html"> <p>Hello, {{name}}, how are you?</p> </script>
./templates/templates.htm源码
<script id="footer-fragment" type="text/html"> <p>© Jonny {{year}}</p> </script> <script id="webcontent" type="text/html"> <h1><blink>My {{adjective}} WebSite!</blink></h1> {{! Insert the `footer-fragment` template below }} {{>footer-fragment}} </script>