Mustache模板

通用模板引擎

mustache.js 用JS对象加工出内容
https://github.com/janl/mustache.js/

logic-less,模板中没有if-else,for-loop,只有标签

调用方法


渲染很简单,提供模板和对象,返回渲染后结果

1
Mustache.render(template, obj);

如果多次使用可以预编译模板,会放入内部cache缓存起来

1
Mustache.parse(template);

模板可以单独写在script标签内,使用时读出

1
2
3
<script id="template" type="x-tmpl-mustache">
Hello {{ name }}!
</script>
1
2
3
let template = document.getElementById('template').innerHTML
let rendered = Mustache.render(template, {name: "World"})
document.getElementById('target').innerHTML = rendered

也可以存成单独的.mustache文件,使用时发送请求模板资源

标签


标准标签是双大括号 {{ }} ,可以采用其他符号自定义标签

  • 单次渲染修改
    改动渲染函数的第四参数
1
Mustache.render(template, view, {}, [ '<%', '%>' ]);
  • 全局修改
1
Mustache.tags = [ '<%', '%>' ];
  • 模板中修改
1
2
3
{{ default_tags }}
{{=<% %>=}}
<% erb_style_tags %>

{{prop}}


模板中标签替换成对象值
如果是值,显示属性值

1
2
3
4
5
let obj = {
hello: 'Hello',
world: 'World'
}
let result = Mustache.render('{{ hello }} {{ world }}!', obj) //Hello World!

如果是函数,先执行函数,再显示函数返回值

1
2
3
4
5
6
7
8
let obj = {
hello: 'Hello',
world: 'World',
helloworld: function() {
return this.hello + ' ' + this.world
}
}
let result = Mustache.render('{{ helloworld }}!', obj) //Hello World!

{{ data }}双大括号是包含HTML转义的, 如果想原样输出可以采用三个括号{{{ data }}}或者{{ &data }}

1
2
3
4
5
let obj = {
hello: '<Hello>',
world: '<World>'
}
let result = Mustache.render('{{ hello }} {{ &world }}', obj) //&lt;Hello&gt; <World>

可以直接用.访问对象嵌套属性

1
2
3
4
5
6
let obj = {
hello: {
world: 'Hello World'
}
}
let result = Mustache.render('{{ hello.world }}', obj) //Hello World

{{#prop}}{{/prop}}


  • if
    控制是否渲染
1
2
3
4
5
6
7
8
let obj = {
showHello: false,
showWorld: function() {
return true
}
}

let result = Mustache.render('{{# showHello }}Hello{{/ showHello }} {{# showWorld }}World{{/ showWorld }}', obj) //World
  • for
    数组循环渲染
    如果是对象数组,可以直接引用当前值的内部属性
1
2
3
4
5
6
let obj = {
data: function() {
return [{ text:'Hello' }, { text:'World' }]
}
}
let result = Mustache.render('{{# data }}{{ text }} {{/ data }}',obj) //Hello World

如果是值数组,可以用{{ . }}表示当前内容

1
2
3
4
5
6
let obj = {
data: function() {
return ['Hello', 'World']
}
}
let result = Mustache.render('{{# data }}{{ . }} {{/ data }}',obj) //Hello World
  • 动态扩展
    用函数扩展原内容
1
2
3
4
5
6
7
8
let obj = {
stress: function() {
return function(text, render) {
return render(text) + '!!!'
}
}
}
let result = Mustache.render('{{# stress }}Hello World{{/ stress }}',obj) //Hello World!!!

{{^prop}}{{/prop}}


反向if逻辑

1
2
3
4
5
6
7
8
let obj = {
showHello: false,
showWorld: function() {
return true
}
}

let result = Mustache.render('{{^ showHello }}Hello{{/ showHello }} {{^ showWorld }}World{{/ showWorld }}', obj) //Hello

{{! This is a comment }}


注释内容,不会进行渲染

{{> partial}}


引用子模板,模块化有助于组合成更加复杂的结构
利用渲染函数第三参数,key是子模板名,value是子模板内容

1
2
3
4
5
6
7
8
9
let obj = {
hello: 'Hello',
world: 'World'
}
let sub = {
first: '{{ hello }}',
second: '{{ world }}'
}
let result = Mustache.render('{{> first}} {{> second}}',obj,sub) //Hello World