1. nunjucks #

Nunjucks是Mozilla开发的一个纯JavaScript编写的模板引擎,既可以用在Node环境下,又可以运行在浏览器端

2. 安装 #

npm install nunjucks

3. 使用 #

3.1 渲染字符串 #

let nunjucks=require('nunjucks');
nunjucks.configure({autoescape: true});
let ret = nunjucks.renderString('hello {{username}}',{username: 'zfpx'});
console.log(ret);

3.2 渲染文件 #

let nunjucks=require('nunjucks');
nunjucks.configure('views',{autoescape:true});
let ret2 = nunjucks.render('index.html',{name: 'zfpx'});
console.log(ret2);

views\index.html

hello {{username}}

3.3 express #

let express=require('express');
const nunjucks=require('nunjucks');
const path=require('path');
let app=express();
nunjucks.configure(path.resolve(__dirname,'views'),{
    autoescape: true,
    express:app
});
app.get('/',function (req,res) {
    res.render('index.html',{name:'zfpx'});
});
app.listen(8080);

4.语法 #

4.1 变量 #

变量会从模板上下文获取,如果你想显示一个变量可以:

{{ username }}

4.2 过滤器 #

过滤器是一些可以执行变量的函数,通过管道操作符 (|) 调用,并可接受参数。

let nunjucks=require('nunjucks');
nunjucks.configure({autoescape: true});
let ret=nunjucks.renderString(`
{{ names | join(",") }}
`,{names: ['name1','name2']});
console.log(ret);

let ret2=nunjucks.renderString(`
{{word| replace("world", "there") | capitalize}}
`,{word:'hello world'});
console.log(ret2);

4.3 if #

if 为分支语句,与 javascript 中的 if 类似。

let nunjucks=require('nunjucks');
nunjucks.configure({autoescape: true});
let ret=nunjucks.renderString(`
{% if score > 90 %}
 优
{% elseif score>80 %}
 良
{% elseif score>70 %}
 中
{% elseif score >60 %}
 及格
{% else %}
 不及格
{% endif %}
`,{score:79});
console.log(ret);

4.4 for #

for 可以遍历数组 (arrays) 和对象 (dictionaries)。

let nunjucks=require('nunjucks');
nunjucks.configure({autoescape: true});
let ret=nunjucks.renderString(`
<ul>
 {% for item in items %}
   <li>{{loop.index}} {{item.id}}:{{item.name}}</li>
   {% endfor %}
</ul>
`,{items: [{id:1,name:'zfpx1'},{id:2,name:'zfpx2'}]});
console.log(ret);

4.5 模板继承 #

4.5.3 login.html #

{% extends "layout.html" %}

{% block content%}
<form action="">
    用户名 <input type="text">
</form>
{% endblock%}

4.6. 包含 #

include 可引入其他的模板,可以在多模板之间共享一些小模板,如果某个模板已使用了继承那么 include 将会非常有用。

4.6.1 index.js #

let nunjucks=require('nunjucks');
const path=require('path');
nunjucks.configure(path.resolve(__dirname,'views'),{autoescape:true});
let ret2=nunjucks.render('items.html',{items: [{id:1,name:'zfpx1'},{id:2,name:'zfpx2'}]});
console.log(ret2);

items.html

{% extends "layout.html" %}

{% block content %}
      <ul>
          {% for item in items %}
          {% include "item.html" %}
        {% endfor %}  
      </ul>
{% endblock %}

item.html

<li>{{item.id}}:{{item.name}}</li>

参考资料 #