官網地址: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就是渲染后的模板。