1、模板引擎最常用的场景是输出网页,我们架构起一定的模板,配合传入的数据,模板的结构不变,但数据会改变。
2、nodejs中,集成了一个nunjucks的环境,在使用的时候引入nunjucks模块就好。nunjucks提供了一个基本的模板语法。
{% extends base.html %}
{% block header %}
<h1>{{title}}</h1>
{% endblock %}
{% block content %}
<ul>
{% for item in array %}
<li>{{item}}</li>
{% endfor %}
</ul>
{% endblock %}
3、在node中nunjucks的使用:
const nunjucks = require("nunjucks");
//创建nunjucks的环境封装函数
function createEnv(path,opts){
var autoescape = opts.autoescape && true,
watch = opts.watch || false,
noCache = opts.noCache || false,
throwOnUndefined = opts.throwOnUndefined || false;
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader({
noCache: noCache,
watch: watch
}),{
autoescape: autoescape,
throwOnUndefined: throwOnUndefined
});
if(opts.filters){
for(var f in opts.filters){
env.addFilter(f,opts.filters[f]);
}
}
return env;
}
//调用封装函数
var env = createEnv('views',{
watch: true,
filters: {
hex:function(n){
return 'Ox' + n.toString(16);
}
}
})
//render视图
var s = env.render('hello.html',{name: "小明"});
console.log(s);