nodejs学习(9)nunjucks模板引擎

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值