Python jinja2 模版使用

发布时间: 更新时间: 总字数:516 阅读时间:2m 作者: 分享 复制网址

总结 python jinja2 模版使用示例。

安装

pip install  jinja2

使用技巧

空行和空格剔除

例如:

{% if xxx %}  # 空行 1
something...
{% endif %}   # 空行 2
              # 空行 3
{% if xxx %}  # 空行 4
something...
{% endif %}   # 空行 5
              # 空行 6
{% if xxx %}  # 空行 7
something...
{% endif %}   # 空行 8

解决方法:

block中加入-符号,例如:

------
{%- if test -%}
{%- endif -%}

{%- if test %}
{% endif -%}

保留 {{ }}

  • rawendraw 中的 {{}} 不会被替换
{% raw %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endraw %}

注释

{# #} 注释,渲染模板时,注释不会包含在最终生成的文件中

示例

示例一

  • 源码
#!/usr/bin/env python
# coding=utf-8

from __future__ import print_function

import os
import sys

from jinja2 import Template


def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read())
        out_file.write(tmle.render(os.environ))


if __name__ == '__main__':
    main()
  • 模版文件 abc.conf.j2
[test]

LANG = "{{ LANG }}"
SHELL = "{{ SHELL }}"

运行:

[root@xiexianbin_cn j2]# ./template.py abc.conf.j2 abc.conf

结果:

[root@xiexianbin_cn j2]# ll
total 12
-rw-r--r-- 1 root root   49 Jan 22 11:35 abc.conf
-rw-r--r-- 1 root root   51 Jan 22 11:35 abc.conf.j2
-rwxr-xr-x 1 root root 1113 Jan 22 10:59 template.py
[root@xiexianbin_cn j2]# cat abc.conf
[test]

LANG = "en_US.UTF-8"
SHELL = "/bin/bash"

示例二

功能:使用jinja 宏(macro)定义函数

  • python 源码
import os
import jinja2


def render(tpl_path, context):
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader('./template')
    ).get_template(filename).render(context)

context = {
    'firstname': 'John',
    'lastname': 'Doe'
}
result = render('./template/my_tpl.html', context)

print(result)
  • 模版文件 template/my_tpl.html
{% highlight html %}
  {% raw %}
{% import 'macro.j2' as form %}
<p>{{ form.input('username') }}</p>
<p>{{ form.input('password', type='password') }}</p>
Hello {{ firstname }} {{ lastname }}!
  {% endraw %}
{% endhighlight %}


- 宏定义文件 template/macro.j2

{% highlight html %}
  {% raw %}
{% macro input(name, value='', type='text', size=20) -%}
    <input type="{{ type }}" name="{{ name }}" value="{{
        value|e }}" size="{{ size }}">
{%- endmacro %}
  {% endraw %}
{% endhighlight %}

运行 & 结果:

[root@xiexianbin_cn jinja2_test]# python j.py

<p><input type="text" name="username" value="" size="20"></p>
<p><input type="password" name="password" value="" size="20"></p>
Hello John Doe!

示例三

for 里面引用变量:

from jinja2 import Template

t = Template("""
{% set x = a %}
My favorite numbers:
{%- for n in range(1,10) %}
  {{n}} {{x}} {{a}}
{%- endfor %}
""")

print(t.render(a="123"))
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数