nunjucks: 学习笔记
一个后端渲染的模板引擎
cheatsheet
用法 | 示例 |
---|---|
变量渲染 |
|
过滤器 |
|
过滤器组合 |
|
自定义 filter |
|
if |
|
if/else |
|
for(array/object) |
|
include |
|
模板继承
- 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 %}
多个导入使用
{% import "forms.html" as forms %}
{{ forms.label('Username') }}
{{ forms.field('user') }}
{{ forms.label('Password') }}
{{ forms.field('pass', type='password') }}
或者
{% from "forms.html" import input, label as description %}
{{ description('Username') }}
{{ input('user') }}
{{ description('Password') }}
{{ input('pass', type='password') }}
单个的导入
{% from "./commons/macros/latest-courses.tpl" import latestCourses %}
# 使用
{{ latestCourses(model) }}