jingja2

官方:http://docs.jinkan.org/docs/jinja2/api.html#unicode

简介

Jinja2 是一个现代的,设计者友好的,仿照 Django 模板的 Python 模板语言。 它速度快,被广泛使用,并且提供了可选的沙箱模板执行环境保证安全

特性:
沙箱中执行
强大的 HTML 自动转义系统保护系统免受 XSS
模板继承
及时编译最优的 python 代码
可选提前编译模板的时间
易于调试。异常的行数直接指向模板中的对应行。
可配置的语法

这个模板中包含了两种标记符
{% … %} 执行一个循环或者一个赋值语句,
{{ … }} 打印一个变量。

API

在这里插入图片描述

1.基础

在这里插入图片描述

Unicode

Jinja2 内部使用 Unicode ,这意味着你需要向渲染函数传递 Unicode 对象或只包含 ASCII 字符的字符串。此外,换行符按照默认 UNIX 风格规定行序列结束( \n )。

Python 2.x 支持两种表示字符串对象的方法。一种是 str 类型,另一种是 unicode 类型,它们都继承于 basestring 类型。
在模块层指定 unicode 为默认值,而在 Python 3 中会是默认值。

要显式使用一个 Unicode 字符串,你需要给字符串字面量加上 u 前缀: u’Hänsel und Gretel sagen Hallo’ 。这样 Python 会用当前模块的字符编码来 解码字符串,来把字符串存储为 Unicode 。如果没有指定编码,默认是 ASCII , 这意味着你不能使用任何非 ASCII 的标识符。

在使用 Unicode 字面量的 Python 模块的首行或第二行添加下面的注释,来妥善设 置模块编码:

#-- coding: utf-8 --
在这里插入图片描述

3.高层 API

高层 API 即是你会在应用中用于加载并渲染模板的 API 。 低层 API 相反,只在你想深入挖掘 Jinja2 或 开发扩展 时有用。

class jinja2.Environment([options])
在这里插入图片描述

4.自动转义

在这里插入图片描述

5.标识符的说明

在这里插入图片描述

6.未定义类型

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

7.上下文

类jinja2.runtime.context

模板上下文保存模板的变量。它存储传递给模板的值以及模板导出的名称。创建实例既不受支持也不有用,因为它是在模板评估的各个阶段自动创建的,不应该手工创建。

上下文是不可变的。不能对父级进行修改,只允许从生成的模板代码中对var进行修改。模板筛选器和标记为ContextFunction()的全局函数获取作为第一个参数传递的活动上下文,并允许以只读方式访问上下文。

模板上下文支持只读dict操作(get、keys、values、items、iterkeys、itervalues、iteritems、getitem、contains)。此外,还有一个**resolve()**方法,它不会因keyError而失败,但会为缺少的变量返回未定义的对象。


parent
一个模板查找的只读全局变量的词典。这些变量可能来自另一个 Context ,或是 Environment.globals ,或是 Template.globals ,或指向一个由全局变量和传递到渲染函数的变 量联立的字典。它一定不能被修改。

vars
模板局域变量。这个列表包含环境和来自 parent 范围的上下文函数 以及局域修改和从模板中导出的变量。模板会在模板求值时修改这个字典, 但过滤器和上下文函数不允许修改它。

environment
加载该模板的环境

exported_vars
这设定了所有模板导出量的名称。名称对应的值在 vars 字典中。 可以用 get_exported() 获取一份导出变量的拷贝字典。

name
拥有此上下文的模板的载入名。

blocks
模板中块当前映射的字典。字典中的键是块名称,值是注册的块的列表。每个 列表的最后一项是当前活动的块(继承链中最新的)。

eval_ctx
当前的 求值上下文 。

call(callable, *args, **kwargs)
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a contextfunction() or environmentfunction().

get_all()
Return a copy of the complete context as dict including the exported variables.

get_exported()
Get a new dict with the exported variables.

resolve(key)
Looks up a variable like getitem or get but returns an Undefined object with the name of the name looked up.

实现
Python frame 中的局域变量在函数中是不可变的,出于同样的原因,上下文是不可 变的。 Jinja2 和 Python 都不把上下文/ frame 作为变量的数据存储,而只作为 主要的数据源。

当模板访问一个模板中没有定义的变量时, Jinja2 在上下文中查找变量,此后, 这个变量被视为其是在模板中定义得一样。

8.加载器

在这里插入图片描述
get_source(environment, template)
Get the template source, filename and reload helper for a template. It’s passed the environment and template name and has to return a tuple in the form (source, filename, uptodate) or raise a TemplateNotFound error if it can’t locate the template.

The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise None. The filename is used by python for the tracebacks if no loader extension is used.

The last item in the tuple is the uptodate function. If auto reloading is enabled it’s always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns False the template will be reloaded.

load(environment, name, globals=None)
Loads a template. This method looks up the template in the cache or loads one by calling get_source(). Subclasses should not override this method as loaders working on collections of other loaders (such as PrefixLoader or ChoiceLoader) will not call this method but get_source directly.

9.字节码缓存

含义:字节码缓存使得在首次使用时把生成的字节码 存储到文件系统或其它位置来避免处理模板。
应用场景:这在当你有一个在首个应用初始化的 web 应用, Jinja 一次性编译大量模板拖慢应用时尤其 有用。

原理:要使用字节码缓存,把它实例化并传给 Environment 。
在这里插入图片描述
在这里插入图片描述

10.实用工具

这些辅助函数和类在你向 Jinja2 环境中添加自定义过滤器或函数时很有用。
在这里插入图片描述
在这里插入图片描述

class jinja2.Markup([string])

在这里插入图片描述
在这里插入图片描述
Note
Jinja2 的 Markup 类至少与 Pylons 和 Genshi 兼容。预计不久更多模板 引擎和框架会采用 html 的概念。

11.异常

exception jinja2.TemplateError(message=None)
Baseclass for all template errors.

exception jinja2.UndefinedError(message=None)
Raised if a template tries to operate on Undefined.

exception jinja2.TemplateNotFound(name, message=None)
Raised if a template does not exist.

exception jinja2.TemplatesNotFound(names=(), message=None)
Like TemplateNotFound but raised if multiple templates are selected. This is a subclass of TemplateNotFound exception, so just catching the base exception will catch both.

New in version 2.2.

exception jinja2.TemplateSyntaxError(message, lineno, name=None, filename=None)
Raised to tell the user that there is a problem with the template.

message
错误信息的 utf-8 字节串。

lineno
发生错误的行号。

name¶
模板的加载名的 unicode 字符串。

filename
加载的模板的文件名字节串,以文件系统的编码(多是 utf-8 , Windows 是 mbcs )。

文件名和错误消息是字节串而不是 unicode 字符串的原因是,在 Python 2.x 中,不对异常和回溯使用 unicode ,编译器同样。这会在 Python 3 改变。

exception jinja2.TemplateAssertionError(message, lineno, name=None, filename=None)
Like a template syntax error, but covers cases where something in the template caused an error at compile time that wasn’t necessarily caused by a syntax error. However it’s a direct subclass of TemplateSyntaxError and has the same attributes.

12.自定义过滤器

自定义过滤器只是常规的 Python 函数,过滤器左边作为第一个参数,其余的参数作 为额外的参数或关键字参数传递到过滤器。
在这里插入图片描述

13.求值上下文

求值上下文(缩写为 eval context 或 eval ctx )是 Jinja 2.4 中引入的新对象, 并可以在运行时激活/停用已编译的特性。

当前它只用于启用和禁用自动转义,但也可以用于扩展

在之前的 Jinja 版本中,过滤器和函数被标记为环境可调用的来从环境中检查自动 转义的状态。在新版本中鼓励通过求值上下文来检查这个设定。

在这里插入图片描述

13.自定义测试

测试像过滤器一样工作,只是测试不能访问环境或上下文,并且它们不能链式使用。 测试的返回值应该是 True 或 False 。测试的用途是让模板设计者运行类型和 一致性检查。
在这里插入图片描述

14.全局命名空间在这里插入图片描述

15.低层 API

16.元 API在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值