Nunjucks
VS Code工程结构
use-nunjucks/
|
+- .vscode/
| |
| +- launch.json <-- VSCode 配置文件
|
+- views/
| |
| +- hello.html <-- HTML模板文件
|
+- app.js <-- 入口js
|
+- package.json <-- 项目描述文件
|
+- node_modules/ <-- npm安装的所有依赖包
package.json中添加nunjucks的依赖
"nunjucks": "2.4.2"
views
hello.html
<html>
<head>
<title>Hello {{ name }}</title>
</head>
<body>
<h3>Fruits List</h3>
{% for f in fruits %}
<p>{{ f }}</p>
{% endfor %}
<p>Total: {{ count|hex }}</p>
</body>
</html>
base.html
<html><body>
{% block header %} <h3>Unnamed</h3> {% endblock %}
{% block body %} <div>No body</div> {% endblock %}
{% block footer %} <div>copyright</div> {% endblock %}
</body>
extend.html
{% extends 'base.html' %}
{% block header %}<h1>{{ header }}</h1>{% endblock %}
{% block body %}<p>{{ body }}</p>{% endblock %}
app.js
const nunjucks = require('nunjucks');
function createEnv(path, opts) {
var
autoescape = opts.autoescape === undefined ? true : opts.autoescape,
noCache = opts.noCache || false,
watch = opts.watch || false,
throwOnUndefined = opts.throwOnUndefined || false,
env = new nunjucks.Environment(
new nunjucks.FileSystemLoader(path, {
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 '0x' + n.toString(16);
}
}
});
var s = env.render('hello.html', {
name: '<Nunjucks>',
fruits: ['Apple', 'Pear', 'Banana'],
count: 12000
});
console.log(s);
console.log(env.render('extend.html', {
header: 'Hello',
body: 'bla bla bla...'
}));
package.json
{
"name": "use-nunjucks",
"version": "1.0.0",
"description": "Test nunjucks",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [
"nunjucks",
"templating"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {
"nunjucks": "2.4.2"
}
}
终端命令
node app.js