在node中使用模板引擎
- 安装模板引擎 npm install art-template
- 加载 require(‘art-template’)
var template = require('art-template')
- 查文档https://aui.github.io/art-template/,使用模板引擎的API
var tplStr = var tplStr = 'my name is {{name}}. I am {{age}}. I like {{each hobbies}}{{$index}}{{$value}}{{/each}}'
var ret = template.render(tplStr,{
name:'xiaobai',
age: 23,
hobbies: ['xx','xx']
}
console.log(ret)
在html中使用模板引擎
在html中使用模板引擎需要引用 lib/template-web.js 文件, script type = “text/template”
<script src="node_modules/art-template/lib/template-web.js"></script>
<script type="text/template" id="tpl">
大家好,我叫:{{ name }}
我今年 {{ age }} 岁了
我喜欢:{{each hobbies}} {{ $value }} {{/each}}
其他跟node一样,只是方法用template()
<script>
vat ret = template(tpl,{
name:'xiaobai',
age: 23,
hobbies: ['xx','xx']
}
console.log(ret)
</script>
我觉得模板引擎的好处是可以用特殊语法去替换数据中需要替换的部分,而不用大规模去替换,而且可以用循环。还有很多不懂的,慢慢摸索吧。