基本的使用
const nunjucks = require('nunjucks') // nunjucks.configure({ autoescape: true }); // const result = nunjucks.renderString('Hello {{ username }}', { username: 'James' }); // console.log(result) // 这里的 views 相对路径是受 node 执行路径影响的 nunjucks.configure('views', { autoescape: true }); // var result = nunjucks.render('index.html', { foo: 'bar' }); var result = nunjucks.render('login.html'); console.log(result)
login.html
{% extends "layout.html" %} {% block body %} <h1>这是登陆页</h1> {% endblock %} {% block script %} <script> window.alert('hello login') </script> {% endblock %}
layout.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="normalize.css"> {% block style %} {% endblock %} </head> <body> {% include "header.html" %} {% include "sidebar.html" %} {% block body %} {% endblock %} {% include "footer.html" %} <script src="jquery.js"></script> {% block script %} {% endblock %} </body> </html>
还有header和sidebar和foot都是属于布局里的公共样式,block遵循一个萝卜一个坑原则,自己写特殊的部分。
来源:https://www.cnblogs.com/ygjzs/p/12232159.html