const data = {
name: "aric",
city: "sh",
nested: {
prop1: "value1",
},
};
const tpl = "Hello {{ name }}, you are from {{ city }}. nested value is : {{ nested.prop1 }}";
const output = nunjucks.renderString(tpl, data);
console.log(output);
var nunjucks = require('nunjucks');
var env = new nunjucks.Environment();
env.addFilter('shorten', function(str, count) {
return str.slice(0, count || 5);
});
=========== usage ================
{# Show the first 5 characters #}
A message for you: {{ message|shorten }}
{# Show the first 20 characters #}
A message for you: {{ message|shorten(20) }}
if
{% if variable %}
It is true
{% endif %}
if/else
{% if hungry %}
I am hungry
{% elif tired %}
I am tired
{% else %}
I am good!
{% endif %}
for(array/object)
const nunjucks = require("nunjucks");
nunjucks.configure("src");
const tmpl = `
<ul>
{% for key, value in food %}
<li>Use {{ value }} of {{ key }}</li>
{% endfor %}
</ul>
`;
const output = nunjucks.renderString(tmpl, {
food: {
ketchup: "5 tbsp",
mustard: "1 tbsp",
pickle: "0 tbsp",
},
});
include
{% include "item.html" %}
循环中的特殊变量
{% for x, y, z in points %}
Point: {{ x }}, {{ y }}, {{ z }}
{% endfor %}
在循环中可获取一些特殊的变量
loop.index: 当前循环数 (1 indexed)
loop.index0: 当前循环数 (0 indexed)
loop.revindex: 当前循环数,从后往前 (1 indexed)
loop.revindex0: 当前循环数,从后往前 (0 based)
loop.first: 是否第一个
loop.last: 是否最后一个
loop.length: 总数
模板继承
parent(一般网站,这个就是 layout)
child
parent.tpl
{% block header %}
This is the default content
{% endblock %}
<section class="left">
{% block left %}{% endblock %}
</section>
<section class="right">
{% block right %}
This is more content
{% endblock %}
</section>
child.tpl
{% extends "parent.html" %}
{% block left %}
This is the left side!
{% endblock %}
{% block right %}
This is the right side!
{% endblock %}
最终 render 的 html 结果为
This is the default content
<section class="left">
This is the left side!
</section>
<section class="right">
This is the right side!
</section>
如果父级的内容是需要的可以使用 super
{% block right %}
{{ super() }}
Right side!
{% endblock %}
Macro
多个(一个 tpl中定义多个)
单个(一个tpl 中定义单个)
多个的场景
{% macro field(name, value='', type='text') %}
<div class="field">
<input type="{{ type }}" name="{{ name }}"
value="{{ value | escape }}" />
</div>
{% endmacro %}
{% macro label(text) %}
<div>
<label>{{ text }}</label>
</div>
{% endmacro %}