Jinja2 is a library found at http://jinja.pocoo.org/; you can use it to produce formatted text with bundled logic.

Imagine a variable x has its value set
to <b>b</b>. If auto-escaping is enabled, {{ x }} in a template would print the string as given. If auto-escaping

is off, which is the Jinja2 default (Flask's default is on), the resulting text would be b.

Double curly braces are a delimiter that allows you to evaluate a variable or function from the provided context and print it into the template:

from jinja2 import Template

# create the template

t = Template("{{ variable }}")

# – Built-in Types –

t.render(variable='hello you')

>> u"hello you"

t.render(variable=100)

>> u"100"

# you can evaluate custom classes instances

class A(object):

def __str__(self):

return "__str__"

def __unicode__(self):

return u"__unicode__"

def __repr__(self):

return u"__repr__"

# – Custom Objects Evaluation –

# __unicode__ has the highest precedence in evaluation

# followed by __str__ and __repr__

t.render(variable=A())

>> u"__unicode__"

First, we evaluate a string and then an integer. Both result in a unicode string. If we evaluate a class of our own, we must make sure there is a __unicode__ method de ned, as it is called during the evaluation. If a __unicode__ method is not de ned, the evaluation falls back to __str__ and __repr__, sequentially. This is easy.

from jinja2 import Template

# create the template

t = Template("{{ fnc() }}")

t.render(fnc=lambda: 10)

>> u"10"

# evaluating a function with argument

t = Template("{{ fnc(x) }}")

t.render(fnc=lambda v: v, x='20')

>> u"20"

t = Template("{{ fnc(v=30) }}")

t.render(fnc=lambda v: v)

>> u"30"

inja2 also has the curly braces/percentage delimiter, which uses the notation {% stmt %} and is used to execute statements, which may be a control statement or not. Its usage depends on the statement, where control statements have the following notation:

{% stmt %}

{% endstmt %}

A last delimiter you should know is{# comments go here #}.Itisamulti-line delimiter used to declare comments.

As a design decision to avoid confusion, all Jinja2 templates have a lowercase alias for True, False, and None.
By the way, lowercase syntax is the preferred way to go.

When building HTML lists, it's a common requirement to mark each list item
in alternating colors in order to improve readability or mark the rst or/and
last item with some special markup. Those behaviors can be achieved in a Jinja2 for-loop through access to a loop variable available inside the block context. Let's see some examples: 

{% for i in ['a', 'b', 'c', 'd'] %}

{% if loop.first %}This is the first iteration{% endif %}

{% if loop.last %}This is the last iteration{% endif %}

With Jinja2, the else block is executed when the for iterable is empty.

the Jinja2 for loop does not support break or continue. Instead, to achieve the expected behavior, you should use loop ltering as follows: 

{% for i in [1, 2, 3, 4, 5] if i > 2 %}

value: {{ i }}; loop.index: {{ loop.index }}

{%- endfor %}

You should consider that condition as a real list lter, as the index itself is only counted per iteration.

do you see the dash in {%-? It tells the renderer that there should be no empty new lines before the tag at each iteration.

block and extends always work together. The rst is used to de ne "overwritable" blocks in a template, while the second de nes a parent template that has blocks

he include statement is probably the easiest statement so far. It allows you to render a template inside another in a very easy fashion.

Finally, we have the set statement. It allows you to de ne variables for inside the template context. Its use is pretty simple: 

{% set x = 10 %}

{{ x }}

{% set x, y, z = 10, 5+5, "home" %}

{{ x }} - {{ y }} - {{ z }}

Macros are the closest to coding you'll get inside Jinja2 templates. The macro de nition and usage are similar to plain Python functions

{% macro input(name, value='', label='') %}

{% if label %}

<label for='{{ name }}'>{{ label }}</label>

{% endif %}

<input id='{{ name }}' name='{{ name }}' value='{{ value }}'></input>

{% endmacro %}

we could even rename our input macro like this:

{% from 'formfield.html' import input as field_input %} You can also import formfield as a module and use it as follows:

{% import 'formfield.html' as formfield %}

When using macros, there is a special case where you want to allow any named argument to be passed into the macro, as you would in a Python function (for example, **kwargs). With Jinja2 macros, these values are, by default, available in a kwargs dictionary that does not need to be explicitly de ned in the macro signature.

kwargs is available even though you did not de ne a kwargs argument in the macro signature.

  • Extensions are the way Jinja2 allows you to extend its vocabulary. Extensions are not enabled by default, so you can enable an extension only when and if you need, and start using it without much trouble:
       env = Environment(extensions=['jinja2.ext.do',
  • 'jinja2.ext.with_'])
  • In the preceding code, we have an example where you create an environment with two extensions enabled: do and with.

% set x = {1:'home', '2':'boat'} %}

{% do x.update({3: 'bar'}) %}

{%- for key,value in x.items() %}

{{ key }} - {{ value }}

{%- endfor %}

In the preceding example, we create the x variable with a dictionary, then we update it with {3: 'bar'}. You don't usually need to use the do extension but, when you do, a lot of coding is saved. 

The with extension is also very simple. You use it whenever you need to create block scoped variables. Imagine you have a value you need cached in a variable for a brief moment; this would be a good use case. Let's see an example:

{% with age = user.get_age() %}

My age: {{ age }}

{% endwith %}

My age: {{ age }}{# no value here #}

As seen in the example, age exists only inside the with block. Also, variables set inside a with block will only exist inside it. For example:

{% with %}

{% set count = query.count() %}

Current Stock: {{ count }}

Diff: {{ prev_count - count }}

{% endwith %}

{{ count }} {# empty value #}

Filters are a marvelous thing about Jinja2! This tool allows you to process a constant or variable before printing it to the template. The goal is to implement the formatting you want, strictly in the template.

To use a lter, just call it using the pipe operator like this:

{% set name = 'junior' %}

{{ name|capitalize }} {# output is Junior #}

{{ ['Adam', 'West']|join(' ') }} {# output is Adam West #}

{# prints default value if input is undefined #}

{{ x|default('no opinion') }}

{# prints default value if input evaluates to false #}

{{ none|default('no opinion', true) }}

{# prints input as it was provided #}

{{ 'some opinion'|default('no opinion') }}

{# you can use a filter inside a control statement #}

{# sort by key case-insensitive #}

{% for key in {'A':3, 'b':2, 'C':1}|dictsort %}{{ key }}{% endfor %}

{# sort by key case-sensitive #}

{% for key in {'A':3, 'b':2, 'C':1}|dictsort(true) %}{{ key }}{%

endfor %}

{# sort by value #}

{% for key in {'A':3, 'b':2, 'C':1}|dictsort(false, 'value') %}{{ key

}}{% endfor %}

{{ [3, 2, 1]|first }} - {{ [3, 2, 1]|last }}

{{ [3, 2, 1]|length }} {# prints input length #}

{# same as in python #}

{{ '%s, =D'|format("I'm John") }}

{{ "He has two daughters"|replace('two', 'three') }}

{# safe prints the input without escaping it first#}

{{ '<input name="stuff" />'|safe }}

{{ "there are five words here"|wordcount }}

As Flask manages the Jinja2 environment for you, you don't have to worry about creating le loaders and stuff like that. One thing you should be aware of, though, is that, because you don't instantiate the Jinja2 environment yourself, you can't really pass to the class constructor, the extensions you want to activate.

To activate an extension, add it to Flask during the application setup as follows: 

from flask import Flask

app = Flask(__name__)

app.jinja_env.add_extension('jinja2.ext.do')  # or jinja2.ext.with_

if __name__ == '__main__':

app.run()

Now, what if you want all your views to have a speci c value in their context, like a version value—some special code or function; how would you do it? Flask offers you the context_processor decorator to accomplish that. You just have to annotate a function that returns a dictionary and you're ready to go. For example:

from flask import Flask, render_response

app = Flask(__name__)

@app.context_processor

def luck_processor():

from random import randint

def lucky_number():

return randint(1, 10)

return dict(lucky_number=lucky_number)

@app.route("/")

def hello():

# lucky_number will be available in the index.html context by

default

return render_template("index.html")

flask之Jinja2的更多相关文章

  1. flask的jinja2模板中过过滤器的相关小内容

    jinja2模板中有自带的过滤器,有需要直接拿来使用.也可以自己定义过滤器 在过滤器中,有一些常见得操作及关键字.有对字符串的操作,还有对大小写转换的操作.还有对list的操作 过滤器的语法 {# 过 ...

  2. Flask中jinja2的应用

    Flask中jinja2的应用 # -*- coding: utf-8 -*- # @Time : 2019/9/24 17:29 # @Author : AnWen from flask impor ...

  3. 【Flask】 Jinja2模板语言

    Jinja2 Jinja2是Python Web编程中的主流模板语言.因为flask是基于Jinja2和Werkzeug发展而来,在安装flask的时候jinja2自动就被装在上面了. 之前提到了很多 ...

  4. 怎么用Python Flask模板jinja2在网页上打印显示16进制数?

    问题:Python列表(或者字典等)数据本身是10进制,现在需要以16进制输出显示在网页上 解决: Python Flask框架中 模板jinja2的If 表达式和过滤器 假设我有一个字典index, ...

  5. flask之jinja2模板语言

    一.jinja2简单介绍 Jinja2是Python里一个被广泛应用的模版引擎,他的设计思想来源于Django的模板引擎,并扩展了其语法和一系列强大的功能.其中最显著的一个是增加了沙箱执行功能和可选的 ...

  6. Flask的jinja2模板中自定义过滤器的使用

    大部分的模板引擎都是支持过滤器功能的,jinja2也不例外,它提供了丰富的内置过滤器,但是有些时候还是没办法满足我们的需求,好在jinja2支持自定义过滤器,下面是一个简单的例子. 下面的例子完成了自 ...

  7. Flask(Jinja2) 服务端模板注入漏洞(SSTI)

    flask Flask 是一个 web 框架.也就是说 Flask 为你提供工具,库和技术来允许你构建一个 web 应用程序.这个 wdb 应用程序可以使一些 web 页面.博客.wiki.基于 we ...

  8. 2.flask模板--jinja2

    1.jinja2模板介绍和查找路径 import os from flask import Flask, render_template # 之前提到过在渲染模板的时候,默认会从项目根目录下的temp ...

  9. flask 渲染jinja2模版和传参

    渲染模版(html文件) A.模版文件(html)放入到template目录下,项目启动的时候会从template目录里查找, B.从flask中导入“render_tempalte”函数 C.在视图 ...

随机推荐

  1. 【收藏】SearchCrawler By James Holmes

    转自Crawling the Web with Java By James Holmes 无需任何扩展包,可直接运行. import java.awt.*; import java.awt.event ...

  2. 20145231《Java程序设计》第三次实验报告

    实验三 敏捷开发与XP实现 实验内容 XP基础 XP核心实践 相关工具 实验要求 了解敏捷开发的基本方法以及XP软件开发的相关准则:了解代码编写的标准和原则:体会结对编程的好处: 实践体会版本控制的方 ...

  3. 3.6《深入理解计算机系统》笔记(四)虚拟存储器,malloc,垃圾回收【插图】

    概述 ●我们电脑上运行的程序都是使用虚拟存储,跟物理内存根本不搭边. ●既然虚拟内存是在磁盘上的,为什么它又运行这么好,并没有感觉卡顿?这要感谢程序的局部性! ●虚拟存储器的调度是一个操作系统必须做好 ...

  4. Python 条件判断语句(if ,elif, else)

    条件判断可以分: 单分支判断:只有一个if语句 双分支判断:if else 的格式 多分支判断:if elif  else 的格式 条件语句嵌套判断 # 下面是个条件多分支判断 score = 85 ...

  5. FreeMarker 使用实例

    以下内容全部是网上收集: FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 1,文本:直接输出的部分 2,注释:<#-- ... - ...

  6. Luogu-2495 [SDOI2011]消耗战

    虚树第一题 对于每次询问的点建立一棵虚树,然后在树上DP,一个点的答案就是这个点的父边切断的代价与所有儿子切断的代价去最小值,当然如果这个节点是资源点则必须切父边 注意在虚树上一条边的代价应该是中间所 ...

  7. Mysql -- You can't specify target table 'address' for update in FROM clause

    做地址管理时,需要先根据要设为默认的地址的用户将用户的其他地址都设置为非默认 需要select出用户id然后update 原语句 update address set isdeafult = 0 wh ...

  8. KVM Best practice

    使用block设备来避免额外的software layers. Best practices: Asynchronous I/O model for KVM guests 尽管KVM supports ...

  9. Tedis:淘宝的Redis的Java客户端开发包

    Tedis:淘宝的Redis的Java客户端开发包   http://www.open-open.com/lib/view/open1389880631976.html   Tedis Tedis是另 ...

  10. 高性能Js—数据存取

    数据存取 JavaScript中四中基本的数据存取位置 字面量:不存于某个变量内 本地变量:var定义的 数组元素 对象成员 字面量.全局变量读取速度 > 数组项.对象成员 .因为局部变量存在于 ...