Jinja2

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")

时间: 2024-08-08 21:54:32

Jinja2的相关文章

[Jinja2]本地加载html模板

import os from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('.')) template = env.get_template('index.html') print(template.render()) 然而Django也能做到 只是貌似需要配置或者创建完整的Django项目app才行

Django1.10配置Jinja2模板

1.安装Jinja2模块: pip install jinja2 2.配置settings: TEMPLATES = [     {         'BACKEND': 'django.template.backends.jinja2.Jinja2',         'DIRS': [os.path.join(BASE_DIR, 'templates')],         'APP_DIRS': True,         'OPTIONS': {             'environ

Python自定义web框架、Jinja2

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦. python标准库提供的独立WSGI服务器称为wsgiref. 标准Web框架 #!/usr/bin/env python #coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ,

自定义jinja2 过滤器

今天,我们要讲的是自定义jinja2 过滤器这个知识点,因为官方文档对此一代而过,讲得不够清楚,所以我们专门拿出来讲一下. 例子 例子写了两个自定义过滤器,一个是转换字典到字符串的过滤器,一个是返回当前参数的类型的过滤器. 源代码: https://github.com/lewis617/jinja2-filter filter是个函数 filter是个函数,跟angular的过滤器几乎一模一样.参数就是管道(pipe)前面那个变量.比如   123|myfilter,123就是myFilter

Ansible用于网络设备管理 part 2 对Jinja2 YAML 和 module的理解

虽然很不想用“应该”这个词,但是还是写上了,的确我自己目前就是这么理解的. 那么这个理解就是,Ansible的一个key point 就是总的一个playbook是去依赖很多元素的,就像一开始那个图里画的,如下图 这里面就涉及到它下挂的不管是yml文件还是Jinja2文件,这些文件的内部一定是和Ansible这个东西相紧密关联的,我之前之所以不那么理解就是在于这一点没有弄清楚,再说明白一点就是下面的内容 看到task:下面的东西了么?name, yum, service,还有在Jinja2文件(

Jinja2 简明使用手册

@Jinja2 简明使用手册(转载) 介绍 Jinja是基于python的模板引擎,功能比较类似于于PHP的smarty,J2ee的Freemarker和velocity. 运行需求 Jinja2需要Python2.4以上的版本. 安装 按照Jinja有多种方式,你可以根据需要选择不同的按照方式. 使用easy_install安装 使用easy_install 或pip: #sudo easy_install Jinja2 #sudo pip install Jinja2 这两个工具可以自动从网

JinJa2 源代码分析

学习方式 从 JinJa 2.0 版本开始学习,之前的版本里有不少编译错误,测试用例也不全,可以先看比较完整的 2.0 版本, 弄清楚主要思路,再看之前的提交过程. JinJa 2.0 概要 JinJa2 简介 JinJa2 是一个 Python 实现的模板引擎,模板引擎的作用就是把一个 HTML 模板,以及一些环境变量,生成 HTML 页面.模板引擎的使用, 可以使我们在 Web 开发中,将不变的部分(HTML 模板) 与变化的部分(环境变量)分开.HTML 模板中不仅支持对变量值进行替换,还

Flask Web Development - Flask 模板1 - 模板机制&Jinja2引擎

节选自PartI Chapter3,这个chapter主要讲模板工作原理,这里讲的就是Jinja2这个模板,另外还提到了Flask-Bootstrap及Flask-Moment两个插件,前者对Flask使用Bootstrap做了些封装,后者对moment.js做了些封装.内容较多,估计分开搞. 模板存在的意义 可维护性高的代码是结构良好且整洁的. 当用户在网站注册一个账户时,他在表单里填入邮箱跟密码,并点击提交按钮.在server端就收到一个包含这些数据的request,再由Flask分发到相应

在windows上如何安装python web引擎jinja2

首先要把你的Python文件夹加到环境变量里头去.假设你的Python文件夹位于C:\Python34,那么你需要打开CMD并输入: SETX PATH "%path%;C:\Python34;C:\Python34\Scripts" 然后把 https://bootstrap.pypa.io/get-pip.py 这个文件下载下来,并在CMD中运行: python get-pip.py 这样你的pip管理工具就安装好了,下面你就只要按照如图所示: pip install Jinja2

[Webpy]在webpy中使用jinja2模板

webpy的模板感觉写小的网页还可以,但是如果要是写比较多的html标签就会显得非常乱,于是决定使用jinja2,这个模板类似django的模板,而且跟其他pythonweb框架的兼容性也比较好. 在项目目录下新建一个settings文件 #-*- coding: utf-8 -*- __author__ = 'orangleliu' ''' settings of the project ''' import os import web from web.contrib.template im