美文网首页报告自动化生成
4.1 模板的制作:Jinja2模板介绍

4.1 模板的制作:Jinja2模板介绍

作者: 数据成长之路 | 来源:发表于2018-07-26 15:32 被阅读9次

学习目标

  • 了解jinja2模板常用语句

前期设置

  • 初始化document
  • 定义直接显示jinja2渲染结果的函数render_templ
from jinja2 import Template
class NameDict(object):
    def __getattr__(self, name):
        try:
            return self.name
        except:
            logging.error("Attribute is not exist")
            return None
        
    def __getitem__(self, name):
        return self.__dict__[name]
    
    def __setitem__(self, name, value):
        self.__dict__[name] = value
document = NameDict()
def render_templ(templ):
    t = Template(templ)
    html = t.render(document=document)
    return html

使用{{}}直接生成内容

document['title'] = "This is a title"
templ = "{{ document.title }}"
render_templ(templ)
'This is a title'

循环生成内容

{% for element in element_list %}
{{ element }}
{% endfor %}
templ = """the begin
{% for element in document['title'] %}
{{ element }}
{% endfor %}
the end"""
print(render_templ(templ))
the begin

T

h

i

s

 

i

s

 

a

 

t

i

t

l

e

the end

这里出现了大量的空白,是用于{}外的空白符号并不会在render使自动忽略,若想自动忽略空白,需要在{%加入-,比如

{% for element in element_list -%}
{{ element }}
{%- endfor %}

就可以去除循环内部的空白。同理

{%- for element in element_list %}
{{ element }}
{% endfor -%}

可以去除外部的空白,有效防止模板排版对生成内容的影响。

templ = """the begin
{% for element in document['title'] -%}
{{ element }}
{%- endfor %}
the end"""
print(render_templ(templ))
the begin
This is a title
the end
templ = """the begin
{%- for element in document['title'] -%}
{{ element }}
{%- endfor -%}
the end"""
print(render_templ(templ))
the beginThis is a titlethe end

赋值

templ = """the begin
{% set element = document['title'] -%}
{{ element }}
the end"""
print(render_templ(templ))
the begin
This is a title
the end

条件语句

document.has_title = True
templ = """the begin
{% if document.has_title -%}
{{ document['title'] }}
{%- endif %}
the end"""
print(render_templ(templ))
the begin
This is a title
the end
document.has_title = False
templ = """the begin
{% if document.has_title -%}
{{ document['title'] }}
{%- endif %}
the end"""
print(render_templ(templ))
the begin

the end

相关文章

网友评论

    本文标题:4.1 模板的制作:Jinja2模板介绍

    本文链接:https://www.haomeiwen.com/subject/anybmftx.html