layout | date | title | tags | categories |
---|---|---|---|---|
post |
2013-02-23 23:45:50 +0800 |
mustache模板引擎 |
javascript template |
javascript template |
What could be more logical awesome than no logic at all?
mustache.js 是 mustache 模板引擎的 js 实现. mustache 支持多种语言,包括 java,php 等.
mustache 的特点是没有复杂的流程控制语句,模板整体看起来清爽自然, 使用数据模型对模板中的标签进行替换.
文件加载,mustache.js 依赖于 jQuery
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/mustache/mustache.js"></script>
使用示例
- demo_1
<!-- demo_1 -->
<div id="target_1">Loading...</div>
<script id="template_1" type="x-tmpl-mustache">
Hello {{ name }}
</script>
<script>
function loadUser() {
var template = $("#template_1").html();
Mustache.parse(template);
var rendered = Mustache.render(template, {
name: "xin"
});
$("#target_1").html(rendered);
}
loadUser();
</script>
- demo_2
<!-- demo_2 -->
<div id="target_2"></div>
<script>
var view = {
title: "Codinglion",
languages: {
JAVA: 'know it',
JS: 'expert'
},
score: function() {
return 90 + 3;
}
};
var output = Mustache.render("{{ title }} learn: {{languages.JAVA}}, {{languages.JS}}. {{score}} score", view);
$("#target_2").html(output);
</script>
- demo_3
<!-- demo_3 -->
<!-- model 加入控制 -->
<div id="target_3"></div>
<script>
var tags = {
"beatles": [{
"firstName": "John",
"lastName": "Lennon"
}, {
"firstName": "Paul",
"lastName": "McCartney"
}, {
"firstName": "George",
"lastName": "Harrison"
}, {
"firstName": "Ringo",
"lastName": "Starr"
}],
"name": function() {
return this.firstName + " " + this.lastName;
}
}
var output = Mustache.render(" {{#beatles}} * {{name}}<br> {{/beatles}} ", tags);
$("#target_3").html(output);
</script>