golang-pongo2模板引擎

本文详细介绍了Go语言中的模板引擎pongo2,其特性包括兼容Django1.7的语法,支持复杂的表达式、函数调用以及自定义过滤器和标签。同时,文章通过示例展示了如何使用pongo2进行模板渲染,并与Django模板语言进行了对比,解释了Django模板的变量、过滤器、标签、模板继承等概念。
摘要由CSDN通过智能技术生成

官网地址: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" }}
View Code

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) }}
View Code

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
View Code

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

VariableDescription
forloop.counterThe current iteration of the loop (1-indexed)
forloop.counter0The current iteration of the loop (0-indexed)
forloop.revcounterThe number of iterations from the end of the loop (1-indexed)
forloop.revcounter0The number of iterations from the end of the loop (0-indexed)
forloop.firstTrue if this is the first time through the loop
forloop.lastTrue if this is the last time through the loop
forloop.parentloopFor 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 %}
ifelif,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就是渲染后的模板。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值