官网地址:https://pkg.go.dev/github.com/flosch/pongo2
模板就是一个简单的文本文件。它可以生成任何基于文本的格式(HTML、XML、CSV、markdown等)。
模板包含变量(在求值时被替换为值)和标签(控制模板的逻辑)。
pongo2是一个模板引擎,类似于jsp
1 特性
1 语法和特性集兼容于Django 1.7,Django模板见官网https://django.readthedocs.io/en/1.7.x/topics/templates.html
2 类C表达式
integers and complex expressions
{{ 10-100 }}
{{ -(10-100) }}
{{ -(-(10-100)) }}
{{ -1 * (-(-(10-100))) }}
{{ -1 * (-(-(10-100)) ^ 2) ^ 3 + 3 * (5 - 17) + 1 + 2 }}
floats
{{ 5.5 }}
{{ 5.172841 }}
{{ 5.5 - 1.5 == 4 }}
{{ 5.5 - 1.5 == 4.0 }}
mul/div
{{ 2 * 5 }}
{{ 2 * 5.0 }}
{{ 2 * 0 }}
{{ 2.5 * 5.3 }}
{{ 1/2 }}
{{ 1/2.0 }}
{{ 1/0.000001 }}
logic expressions
{{ !true }}
{{ !(true || false) }}
{{ true || false }}
{{ true or false }}
{{ false or false }}
{{ false || false }}
{{ true && (true && (true && (true && (1 == 1 || false)))) }}
float comparison
{{ 5.5 <= 5.5 }}
{{ 5.5 < 5.5 }}
{{ 5.5 > 5.5 }}
{{ 5.5 >= 5.5 }}
remainders
{{ (simple.number+7)%7 }}
{{ (simple.number+7)%7 == 0 }}
{{ (simple.number+7)%6 }}
in/not in
{{ 5 in simple.intmap }}
{{ 2 in simple.intmap }}
{{ 7 in simple.intmap }}
{{ !(5 in simple.intmap) }}
{{ not(7 in simple.intmap) }}
{{ 1 in simple.multiple_item_list }}
{{ 4 in simple.multiple_item_list }}
{{ !(4 in simple.multiple_item_list) }}
{{ "Hello" in simple.misc_list }}
{{ "Hello2" in simple.misc_list }}
{{ 99 in simple.misc_list }}
{{ False in simple.misc_list }}
issue #48 (associativity for infix operators)
{{ 34/3*3 }}
{{ 10 + 24 / 6 / 2 }}
{{ 6 - 4 - 2 }}
issue #64 (uint comparison with int const)
{{ simple.uint }}
{{ simple.uint == 8 }}
{{ simple.uint == 9 }}
{{ simple.uint >= 8 }}
{{ simple.uint <= 8 }}
{{ simple.uint < 8 }}
{{ simple.uint > 8 }}
string concatenation
{{ "a" + "b" }}
{{ 1 + "a" }}
{{ "a" + "1" }}
3 表达式中的复杂函数调用
{{ simple.func_add(simple.func_add(5, 15), simple.number) + 17 }}
{{ simple.func_add_iface(simple.func_add_iface(5, 15), simple.number) + 17 }}
{{ simple.func_variadic("hello") }}
{{ simple.func_variadic("hello, %s", simple.name) }}
{{ simple.func_variadic("%d + %d %s %d", 5, simple.number, "is", 49) }}
{{ simple.func_variadic_sum_int() }}
{{ simple.func_variadic_sum_int(1) }}
{{ simple.func_variadic_sum_int(1, 19, 185) }}
{{ simple.func_variadic_sum_int2() }}
{{ simple.func_variadic_sum_int2(2) }}
{{ simple.func_variadic_sum_int2(1, 7, 100) }}
4 易于创建新的过滤器和标记的API(包括解析参数)
5 宏
Begin
{% macro greetings(to, from=simple.name, name2="guest") %}
Greetings to {{ to }} from {{ from }}. Howdy, {% if name2 == "guest" %}anonymous guest{% else %}{{ name2 }}{% endif %}!
{% endmacro %}
{{ greetings() }}
{{ greetings(10) }}
{{ greetings("john") }}
{{ greetings("john", "michelle") }}
{{ greetings("john", "michelle", "johann") }}
{% macro test2(loop, value) %}map[{{ loop.Counter0 }}] = {{ value }}{% endmacro %}
{% for item in simple.misc_list %}
{{ test2(forloop, item) }}{% endfor %}
issue #39 (deactivate auto-escape of macros)
{% macro html_test(name) %}
<p>Hello {{ name }}.</p>
{% endmacro %}
{{ html_test("Max") }}
Importing macros
{% import "macro.helper" imported_macro, imported_macro as renamed_macro, imported_macro as html_test %}
{{ imported_macro("User1") }}
{{ renamed_macro("User2") }}
{{ html_test("Max") }}
Chaining macros{% import "macro2.helper" greeter_macro %}
{{ greeter_macro() }}
End
2 Django模板语言
上面我们讲过,pongo2语法兼容Django模板语法,我们先看一下Django的模板语言
官网:https://django.readthedocs.io/en/1.7.x/topics/templates.html
模板就是一个简单的文本文件。它可以生成任何基于文本的格式(HTML、XML、CSV等)。
示例
{% extends "base_generic.html" %}
{% block title %}{{ section.title }}{% endblock %}
{% block content %}
<h1>{{ section.title }}</h1>
{% for story in story_list %}
<h2>
<a href="{{ story.get_absolute_url }}">
{{ story.headline|upper }}
</a>
</h2>
<p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}
2.1 变量
{{ variable }}
当模板引擎遇到一个变量时,它将计算该变量并将其替换为结果
2.2 过滤器filter
{{ name|lower }}
上面过滤器lower的作用是把变量name转为小写字母
带参数的过滤器,作用取bio前30个字符 {{ bio|truncatewords:30 }}
用逗号和空格连接一个列表 {{ list|join:", " }}
30多个内嵌的过滤器参考这里:https://django.readthedocs.io/en/1.7.x/ref/templates/builtins.html#ref-templates-builtins-filters
常用的几个过滤器
1 default,给出变量的默认值, {{ value|default:"nothing" }}
2 length, {{ value|length }}
2.3 Tags
格式 {% tag %} 或者 {% tag %} ... tag contents ... {% endtag %}
20多个内嵌的Tag参考这里:https://django.readthedocs.io/en/1.7.x/ref/templates/builtins.html#ref-templates-builtins-tags
常用的几个Tag
1 for
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
for循环预设了几个在循环中使用的变量,并且,我们如果要使用这些变量,需要首字母大写,比如forloop.First
Variable | Description |
---|---|
forloop.counter | The current iteration of the loop (1-indexed) |
forloop.counter0 | The current iteration of the loop (0-indexed) |
forloop.revcounter | The number of iterations from the end of the loop (1-indexed) |
forloop.revcounter0 | The number of iterations from the end of the loop (0-indexed) |
forloop.first | True if this is the first time through the loop |
forloop.last | True if this is the last time through the loop |
forloop.parentloop | For nested loops, this is the loop surrounding the current one |
{% for PCA in reportDataInfo.PCA_list %}
{% if not (forloop.First and forloop.Parentloop.First) %}
---
{% endif %}
2 if
, elif
,else
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
3 autoescape
如果定义为on则,在其范围内的变量将进行html转义。
{% autoescape on %}
{{ body }}
{% endautoescape %}
2.4 模板继承
我们可以通过模板继承,实现
例如,base.html
<html lang="en">
<body>
<div>这是公共部分</div>
<div>
{% block content %}这里可以在子模板中被覆盖{% endblock %}
</div>
</body>
</html>
child.html
{% extends "base.html" %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
3 模板和数据的合并
上面主要讲的是模板的格式、语法等内容。
既然是模板引擎,当然具有渲染数据到模板的功能,下面我们以一个简单的例子进行讲解
tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!")
if err != nil {
panic(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"name": "florian"})
if err != nil {
panic(err)
}
fmt.Println(out) // Output: Hello Florian!
1 通过 pongo2.FromString 或者 pongo2.FromFile 等api返回一个*Template类型的指针,它包含了模板。
2 template.Execute(pongo2.Context{"name": "florian"}) 传递一个类似json的对象 {"name": "florian"} 执行template的Execute进行数据渲染到模板。其返回一个字符串out。out就是渲染后的模板。