API¶
This document describes the API to Jinja and not the template language
(for that, see Template Designer Documentation). It will be most useful as reference
to those implementing the template interface to the application and not
those who are creating Jinja templates.
本文档描述了 Jinja 的 API,而不是模板语言(有关模板语言,请参阅模板设计师文档)。对于那些实现模板接口到应用程序的人来说,它将作为参考最有用,而不是那些创建 Jinja 模板的人。
Basics¶ 基础 ¶
Jinja uses a central object called the template Environment
.
Instances of this class are used to store the configuration and global objects,
and are used to load templates from the file system or other locations.
Even if you are creating templates from strings by using the constructor of
Template
class, an environment is created automatically for you,
albeit a shared one.
Jinja 使用一个称为模板 Environment
的中心对象。该类的实例用于存储配置和全局对象,并用于从文件系统或其他位置加载模板。即使您正在使用 Template
类的构造函数从字符串创建模板,也会为您自动创建一个环境,尽管是共享的。
Most applications will create one Environment
object on application
initialization and use that to load templates. In some cases however, it’s
useful to have multiple environments side by side, if different configurations
are in use.
大多数应用程序将在应用程序初始化时创建一个 Environment
对象,并使用该对象来加载模板。然而,在某些情况下,如果使用不同的配置,同时拥有多个环境是有用的。
The simplest way to configure Jinja to load templates for your
application is to use PackageLoader
.
配置 Jinja 以加载应用程序模板的最简单方法是使用 PackageLoader
。
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader("yourapp"),
autoescape=select_autoescape()
)
This will create a template environment with a loader that looks up
templates in the templates
folder inside the yourapp
Python
package (or next to the yourapp.py
Python module). It also enables
autoescaping for HTML files. This loader only requires that yourapp
is importable, it figures out the absolute path to the folder for you.
这将创建一个模板环境,其中的加载器在 yourapp
Python 包(或 yourapp.py
Python 模块)内的 templates
文件夹中查找模板。它还为 HTML 文件启用了自动转义。此加载器只需要 yourapp
可导入,它会为您找出文件夹的绝对路径。
Different loaders are available to load templates in other ways or from
other locations. They’re listed in the Loaders section below. You can
also write your own if you want to load templates from a source that’s
more specialized to your project.
还有其他可用的加载器以其他方式或从其他位置加载模板。它们在下面的加载器部分中列出。如果您想从更专门于您的项目的源加载模板,您也可以编写自己的加载器。
To load a template from this environment, call the get_template()
method, which returns the loaded Template
.
要从此环境加载模板,请调用 get_template()
方法,该方法返回加载的 Template
。
template = env.get_template("mytemplate.html")
To render it with some variables, call the render()
method.
要使用一些变量进行渲染,请调用 render()
方法。
print(template.render(the="variables", go="here"))
Using a template loader rather than passing strings to Template
or Environment.from_string()
has multiple advantages. Besides being
a lot easier to use it also enables template inheritance.
使用模板加载器而不是将字符串传递给 Template
或 Environment.from_string()
具有多个优势。除了更容易使用外,还可以实现模板继承。
Notes on Autoescaping 自动转义的注意事项
In future versions of Jinja we might enable autoescaping by default
for security reasons. As such you are encouraged to explicitly
configure autoescaping now instead of relying on the default.
在未来的 Jinja 版本中,出于安全考虑,我们可能会默认启用自动转义。因此,建议您现在明确配置自动转义,而不是依赖默认设置。
High Level API¶ 高级 API ¶
The high-level API is the API you will use in the application to load and
render Jinja templates. The Low Level API on the other side is only
useful if you want to dig deeper into Jinja or develop extensions.
高级 API 是应用程序中用于加载和渲染 Jinja 模板的 API。另一方面,低级 API 只有在您想深入了解 Jinja 或开发扩展时才有用。
- class jinja2.Environment([options])¶
The core component of Jinja is the
Environment
. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.
Jinja 的核心组件是Environment
。它包含重要的共享变量,如配置、过滤器、测试、全局变量等。如果实例不是共享的,并且到目前为止还没有加载模板,则可以修改此类的实例。在加载第一个模板后对环境进行修改将导致意想不到的效果和未定义的行为。Here are the possible initialization parameters:
这里是可能的初始化参数:block_start_string
The string marking the beginning of a block. Defaults to
'{%'
.
标记块开始的字符串。默认为'{%'
。block_end_string
The string marking the end of a block. Defaults to
'%}'
.
标记块结束的字符串。默认为'%}'
。variable_start_string
The string marking the beginning of a print statement. Defaults to
'{{'
.
用于标记打印语句开头的字符串。默认为'{{'
。variable_end_string
The string marking the end of a print statement. Defaults to
'}}'
.
用于标记打印语句结尾的字符串。默认为'}}'
。comment_start_string
The string marking the beginning of a comment. Defaults to
'{#'
.
表示注释开始的字符串。默认为'{#'
。comment_end_string
The string marking the end of a comment. Defaults to
'#}'
.
表示注释结束的字符串。默认为'#}'
。line_statement_prefix
If given and a string, this will be used as prefix for line based statements. See also Line Statements.
如果给定并且是一个字符串,将用作行语句的前缀。另请参阅行语句。line_comment_prefix
If given and a string, this will be used as prefix for line based comments. See also Line Statements.
如果给定并且是一个字符串,将用作行注释的前缀。另请参阅行语句。Changelog 更新日志
New in version 2.2.
trim_blocks
If this is set to
True
the first newline after a block is removed (block, not variable tag!). Defaults toFalse
.
如果设置为True
,则块后的第一个换行符将被移除(块,而不是变量标签!)。默认为False
。lstrip_blocks
If this is set to
True
leading spaces and tabs are stripped from the start of a line to a block. Defaults toFalse
.
如果设置为True
,则会从块的开头删除行的前导空格和制表符。默认为False
。newline_sequence
The sequence that starts a newline. Must be one of
'\r'
,'\n'
or'\r\n'
. The default is'\n'
which is a useful default for Linux and OS X systems as well as web applications.
开始新行的序列。必须是'\r'
、'\n'
或'\r\n'
之一。默认值是'\n'
,对于 Linux 和 OS X 系统以及 Web 应用程序来说是一个有用的默认值。keep_trailing_newline
Preserve the trailing newline when rendering templates. The default is
False
, which causes a single newline, if present, to be stripped from the end of the template.
在渲染模板时保留尾随换行符。默认为False
,这会导致模板末尾的单个换行符(如果存在)被删除。Changelog 更新日志
New in version 2.7.
extensions
List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at the extensions documentation.
要使用的 Jinja 扩展列表。这可以是字符串形式的导入路径或扩展类。有关更多信息,请查看扩展文档。optimized
should the optimizer be enabled? Default is
True
.
优化器是否应启用?默认为True
。undefined
Undefined
or a subclass of it that is used to represent undefined values in the template.
Undefined
或其子类,用于表示模板中未定义的值。finalize
A callable that can be used to process the result of a variable expression before it is output. For example one can convert
None
implicitly into an empty string here.
一个可调用的函数,用于在输出变量表达式结果之前对其进行处理。例如,可以在此处将None
隐式转换为空字符串。autoescape
If set to
True
the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping seeMarkup
. As of Jinja 2.4 this can also be a callable that is passed the template name and has to returnTrue
orFalse
depending on autoescape should be enabled by default.
如果设置为True
,则默认情况下启用 XML/HTML 自动转义功能。有关自动转义的更多详细信息,请参阅Markup
。从 Jinja 2.4 开始,这也可以是一个可调用对象,它会传递模板名称并且必须返回True
或False
,具体取决于是否应默认启用自动转义。Changelog 更新日志
Changed in version 2.4:
autoescape
can now be a functionloader
The template loader for this environment.
此环境的模板加载器。cache_size
The size of the cache. Per default this is
400
which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to0
templates are recompiled all the time, if the cache size is-1
the cache will not be cleaned.
缓存的大小。默认情况下为400
,这意味着如果加载的模板超过 400 个,加载器将清除最近最少使用的模板。如果将缓存大小设置为0
,则所有模板将一直重新编译;如果将缓存大小设置为-1
,则不会清除缓存。Changelog 更新日志
Changed in version 2.8: The cache size was increased to 400 from a low 50.
auto_reload
Some loaders load templates from locations where the template sources may change (ie: file system or database). If
auto_reload
is set toTrue
(default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it’s possible to disable that.
一些加载器从模板可能会发生变化的位置加载模板(例如:文件系统或数据库)。 如果auto_reload
设置为True
(默认值),每次请求模板时,加载器都会检查源是否发生了变化,如果是,则重新加载模板。 为了提高性能,可以禁用该功能。bytecode_cache
If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don’t have to be parsed if they were not changed.
如果设置为字节码缓存对象,则该对象将为内部 Jinja 字节码提供缓存,这样模板在未更改的情况下就无需解析。See Bytecode Cache for more information.
有关更多信息,请参阅字节码缓存。enable_async
If set to true this enables async template execution which allows using async functions and generators.
如果设置为 true,则启用异步模板执行,允许使用异步函数和生成器。
- Parameters: 参数:
block_start_string (str) –
block_end_string (str) –
block_end_string (str) – 块结束字符串variable_start_string (str) –
variable_start_string (str) – 变量开始字符串variable_end_string (str) –
variable_end_string (str) – 变量结束字符串comment_start_string (str) –
comment_start_string (str) -comment_end_string (str) –
comment_end_string (str) -line_statement_prefix (str | None) –
line_statement_prefix (str | None) -line_comment_prefix (str | None) –
trim_blocks (bool) – trim_blocks (bool) – 去除空白块
lstrip_blocks (bool) – lstrip_blocks(布尔值)–
newline_sequence (te.Literal['\n', '\r\n', '\r']) –
newline_sequence(te.Literal['\n','\r\n','\r'])–keep_trailing_newline (bool) –
keep_trailing_newline(布尔值)–extensions (Sequence[str | Type[Extension]]) –
扩展 (Sequence[str | Type[Extension]]) -optimized (bool) – 优化 (bool) -
finalize (Callable[[...], Any] | None) –
finalize(Callable[[...], Any] | None)-autoescape (bool | Callable[[str | None], bool]) –
autoescape(bool | Callable[[str | None], bool])-loader (BaseLoader | None) –
loader(BaseLoader | None)-cache_size (int) – cache_size(整数)–
auto_reload (bool) – auto_reload(布尔值)–
bytecode_cache (BytecodeCache | None) –
bytecode_cache(字节码缓存 | 无)–enable_async (bool) – enable_async (bool) – 启用异步
If a template was created by using the
Template
constructor an environment is created automatically. These environments are created as shared environments which means that multiple templates may have the same anonymous environment. For all shared environments this attribute isTrue
, elseFalse
.
如果使用Template
构造函数创建了模板,则会自动创建一个环境。这些环境被创建为共享环境,这意味着多个模板可以具有相同的匿名环境。对于所有共享环境,此属性为True
,否则为False
。
- sandboxed¶ 沙盒化的 ¶
If the environment is sandboxed this attribute is
True
. For the sandbox mode have a look at the documentation for theSandboxedEnvironment
.
如果环境是沙盒化的,则此属性为True
。有关沙盒模式,请参阅SandboxedEnvironment
的文档。
- filters¶ 过滤器 ¶
A dict of filters for this environment. As long as no template was loaded it’s safe to add new filters or remove old. For custom filters see Custom Filters. For valid filter names have a look at Notes on Identifiers.
此环境的过滤器字典。只要没有加载模板,就可以安全地添加新的过滤器或删除旧的过滤器。有关自定义过滤器,请参阅自定义过滤器。有关有效的过滤器名称,请参阅标识符注释。
- tests¶ 测试 ¶
A dict of test functions for this environment. As long as no template was loaded it’s safe to modify this dict. For custom tests see Custom Tests. For valid test names have a look at Notes on Identifiers.
这个环境的测试函数字典。只要没有加载模板,就可以安全地修改这个字典。有关自定义测试,请参阅自定义测试。有关有效的测试名称,请参阅标识符注释。
- globals¶ 全局变量 ¶
A dict of variables that are available in every template loaded by the environment. As long as no template was loaded it’s safe to modify this. For more details see The Global Namespace. For valid object names see Notes on Identifiers.
每个环境加载的模板中都可以使用的变量字典。只要没有加载模板,就可以安全地修改它。有关详细信息,请参阅全局命名空间。有关有效对象名称,请参阅标识符注释。
- policies¶ 策略 ¶
A dictionary with Policies. These can be reconfigured to change the runtime behavior or certain template features. Usually these are security related.
一个包含策略的字典。可以重新配置这些策略以更改运行时行为或某些模板功能。通常与安全相关。
- code_generator_class¶ 代码生成器类 ¶
The class used for code generation. This should not be changed in most cases, unless you need to modify the Python code a template compiles to.
用于代码生成的类。在大多数情况下,除非您需要修改模板编译为的 Python 代码,否则不应更改此类。
- context_class¶ 上下文类 ¶
The context used for templates. This should not be changed in most cases, unless you need to modify internals of how template variables are handled. For details, see
Context
.
用于模板的上下文。在大多数情况下,这不应更改,除非您需要修改模板变量处理的内部。有关详细信息,请参见Context
。
- overlay([options])¶ 覆盖([选项]) ¶
Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions.
创建一个新的叠加环境,该环境与当前环境共享所有数据,但不包括缓存和被覆盖的属性。 无法删除叠加环境的扩展。 叠加环境会自动获取其链接环境的所有扩展,以及可选的额外扩展。Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through.
创建叠加层应在初始环境完全设置完成后进行。并非所有属性都是真正关联的,有些只是复制过来的,因此对原始环境的修改可能不会显现出来。Changed in version 3.1.2: Added the
newline_sequence
,,keep_trailing_newline
, andenable_async
parameters to match__init__
.
在版本 3.1.2 中更改:添加了newline_sequence
,keep_trailing_newline
和enable_async
参数以匹配__init__
。- Parameters: 参数:
block_start_string (str) –
block_start_string(str)-block_end_string (str) –
block_end_string(str)-variable_start_string (str) –
variable_start_string(str)-variable_end_string (str) –
variable_end_string(str)-comment_start_string (str) –
comment_end_string (str) –
line_statement_prefix (str | None) –
line_statement_prefix(字符串 | 空)-line_comment_prefix (str | None) –
line_comment_prefix(字符串 | 空)-trim_blocks (bool) – trim_blocks(布尔值)-
lstrip_blocks (bool) – lstrip_blocks(布尔值)-
newline_sequence (te.Literal['\n', '\r\n', '\r']) –
newline_sequence(te.Literal['\n', '\r\n', '\r'])-keep_trailing_newline (bool) –
keep_trailing_newline(布尔值)–extensions (Sequence[str | Type[Extension]]) –
扩展(序列[str | Type[Extension]])–optimized (bool) – 优化(布尔值)-
finalize (Callable[[...], Any] | None) –
完成(可调用[[...], 任意类型] | 无)-autoescape (bool | Callable[[str | None], bool]) –
autoescape(布尔值 | 可调用[[字符串 | 空], 布尔值])-loader (BaseLoader | None) –
加载器 (BaseLoader | None) –cache_size (int) – 缓存大小 (int) –
auto_reload (bool) – 自动重新加载 (bool) –
bytecode_cache (BytecodeCache | None) –
bytecode_cache(字节码缓存 | 无)-enable_async (bool) – enable_async(布尔值)-
- Return type: 返回类型:
-
undefined([hint, obj, name, exc])¶
未定义([提示,对象,名称,异常])¶ Creates a new
Undefined
object forname
. This is useful for filters or functions that may return undefined objects for some operations. All parameters except ofhint
should be provided as keyword parameters for better readability. Thehint
is used as error message for the exception if provided, otherwise the error message will be generated fromobj
andname
automatically. The exception provided asexc
is raised if something with the generated undefined object is done that the undefined object does not allow. The default exception isUndefinedError
. If ahint
is provided thename
may be omitted.
为name
创建一个新的Undefined
对象。这对于可能对某些操作返回未定义对象的过滤器或函数非常有用。除了hint
之外的所有参数都应该作为关键字参数提供,以便提高可读性。如果提供了hint
,则将其用作异常的错误消息,否则错误消息将从obj
和name
自动生成。如果对生成的未定义对象执行了不允许的操作,则会引发提供的异常exc
。默认异常是UndefinedError
。如果提供了hint
,则可以省略name
。The most common way to create an undefined object is by providing a name only:
创建未定义对象最常见的方法是仅提供名称:return environment.undefined(name='some_name')
This means that the name
some_name
is not defined. If the name was from an attribute of an object it makes sense to tell the undefined object the holder object to improve the error message:
这意味着名称some_name
未定义。如果名称来自对象的属性,则告知未定义对象持有者对象以改进错误消息是有意义的。if not hasattr(obj, 'attr'): return environment.undefined(obj=obj, name='attr')
For a more complex example you can provide a hint. For example the
first()
filter creates an undefined object that way:
对于更复杂的示例,您可以提供一个提示。例如,first()
过滤器以这种方式创建一个未定义的对象:return environment.undefined('no first item, sequence was empty')
If it the
name
orobj
is known (for example because an attribute was accessed) it should be passed to the undefined object, even if a customhint
is provided. This gives undefined objects the possibility to enhance the error message.
如果name
或obj
已知(例如因为访问了属性),即使提供了自定义hint
,也应将其传递给未定义的对象。这样未定义的对象就有可能增强错误消息。
- add_extension(extension)¶
Adds an extension after the environment was created.
在环境创建后添加扩展。Changelog 更新日志
New in version 2.5.
- extend(**attributes)¶
Add the items to the instance of the environment if they do not exist yet. This is used by extensions to register callbacks and configuration values without breaking inheritance.
如果实例环境中的项目尚不存在,则将其添加到其中。这用于扩展注册回调和配置值,而不会破坏继承关系。- Parameters: 参数:
attributes (Any) – 属性(任意类型) -
- Return type: 返回类型:
None 无
-
compile_expression(source, undefined_to_none=True)¶
编译表达式(源代码,未定义转为 None)¶ A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.
一个方便的辅助方法,返回一个可调用对象,该对象接受关键字参数,这些参数在表达式中作为变量出现。如果调用它,它将返回表达式的结果。This is useful if applications want to use the same rules as Jinja in template “configuration files” or similar situations.
如果应用程序希望在模板“配置文件”或类似情况下使用与 Jinja 相同的规则,则这非常有用。Example usage: 用法示例:
>>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True
Per default the return value is converted to
None
if the expression returns an undefined value. This can be changed by settingundefined_to_none
toFalse
.
默认情况下,如果表达式返回未定义的值,则返回值将转换为None
。可以通过将undefined_to_none
设置为False
来更改此设置。>>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined
Changelog 更新日志
New in version 2.1.
- compile_templates(target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True)¶
Finds all the templates the loader can find, compiles them and stores them in
target
. Ifzip
isNone
, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm,zip
can be set to'stored'
.
找到加载器可以找到的所有模板,编译它们并将它们存储在target
中。如果zip
是None
,模板将被存储在一个目录中,而不是一个压缩文件中。默认情况下使用 deflate 压缩算法。要切换到存储算法,可以将zip
设置为'stored'
。extensions
andfilter_func
are passed tolist_templates()
. Each template returned will be compiled to the target folder or zipfile.
extensions
和filter_func
将传递给list_templates()
。每个返回的模板将被编译到目标文件夹或压缩文件中。By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set
ignore_errors
toFalse
and you will get an exception on syntax errors.
默认情况下,模板编译错误会被忽略。如果提供了日志函数,则会记录错误。如果您希望模板语法错误中止编译,您可以将ignore_errors
设置为False
,这样在语法错误时会引发异常。Changelog 更新日志
New in version 2.4.
- Parameters: 参数:
target (str | PathLike[str]) –
target (str | PathLike[str]) -extensions (Collection[str] | None) –
扩展 (Collection[str] | None) -filter_func (Callable[[str], bool] | None) –
filter_func(可调用[[str], bool] | 无)–zip (str | None) –
zip(字符串 | 无)–log_function (Callable[[str], None] | None) –
log_function (Callable[[str], None] | None) -ignore_errors (bool) – ignore_errors(布尔值)–
- Return type: 返回类型:
None 无
- list_templates(extensions=None, filter_func=None)¶
Returns a list of templates for this environment. This requires that the loader supports the loader’s
list_templates()
method.
返回此环境的模板列表。这要求加载器支持加载器的list_templates()
方法。If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either
extensions
is set to a list of file extensions for templates, or afilter_func
can be provided which is a callable that is passed a template name and should returnTrue
if it should end up in the result list.
如果模板文件夹中除了实际模板之外还有其他文件,则可以对返回的列表进行过滤。有两种方法:要么将extensions
设置为模板的文件扩展名列表,要么提供一个filter_func
,它是一个可调用对象,传递一个模板名称,并且如果应该将其放入结果列表中,则应返回True
。If the loader does not support that, a
TypeError
is raised.
如果加载器不支持该功能,则会引发TypeError
。Changelog 更新日志
New in version 2.4.
- join_path(template, parent)¶
Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the
template
parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.
将模板与父模板连接起来。默认情况下,所有查找都相对于加载器的根目录,因此此方法返回template
参数不变,但如果路径应相对于父模板,则可以使用此函数计算真实的模板名称。Subclasses may override this method and implement template path joining here.
子类可以重写此方法并在此处实现模板路径的连接。
-
get_template(name, parent=None, globals=None)¶
get_template(name,parent=None,globals=None) ¶ Load a template by name with
loader
and return aTemplate
. If the template does not exist aTemplateNotFound
exception is raised.
通过名称和loader
加载模板,并返回Template
。如果模板不存在,则会引发TemplateNotFound
异常。- Parameters: 参数:
name (str | Template) – Name of the template to load. When loading templates from the filesystem, “/” is used as the path separator, even on Windows.
name (str | Template) - 要加载的模板的名称。当从文件系统加载模板时,即使在 Windows 上,也使用“/”作为路径分隔符。parent (str | None) – The name of the parent template importing this template.
join_path()
can be used to implement name transformations with this.
parent (str | None) - 导入此模板的父模板的名称。可以使用join_path()
来实现名称转换。globals (MutableMapping[str, Any] | None) – Extend the environment
globals
with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items.
globals(MutableMapping[str, Any] | None)- 使用这些额外变量扩展环境globals
,以便在此模板的所有渲染中都可用。如果模板已经被加载和缓存,其全局变量将会更新为任何新项。
- Return type: 返回类型:
Changelog 更新日志
Changed in version 3.0: If a template is loaded from cache,
globals
will update the template’s globals instead of ignoring the new values.Changed in version 2.4: If
name
is aTemplate
object it is returned unchanged.
-
select_template(names, parent=None, globals=None)¶
select_template(names,parent=None,globals=None) ¶ Like
get_template()
, but tries loading multiple names. If none of the names can be loaded aTemplatesNotFound
exception is raised.
类似于get_template()
,但尝试加载多个名称。如果没有一个名称可以加载,则会引发TemplatesNotFound
异常。- Parameters: 参数:
names (Iterable[str | Template]) – List of template names to try loading in order.
names(Iterable[str | Template])- 要按顺序尝试加载的模板名称列表。parent (str | None) – The name of the parent template importing this template.
join_path()
can be used to implement name transformations with this.
parent(str | None)- 导入此模板的父模板的名称。可以使用join_path()
来实现名称转换。globals (MutableMapping[str, Any] | None) – Extend the environment
globals
with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items.
全局变量(MutableMapping[str, Any] | None)- 使用这些额外变量扩展环境globals
,以便在此模板的所有渲染中都可用。如果模板已经被加载和缓存,其全局变量将会更新为任何新项。
- Return type: 返回类型:
Changelog 更新日志
Changed in version 3.0: If a template is loaded from cache,
globals
will update the template’s globals instead of ignoring the new values.Changed in version 2.11: If
names
isUndefined
, anUndefinedError
is raised instead. If no templates were found andnames
containsUndefined
, the message is more helpful.Changed in version 2.4: If
names
contains aTemplate
object it is returned unchanged.New in version 2.3.
- get_or_select_template(template_name_or_list, parent=None, globals=None)¶
Use
select_template()
if an iterable of template names is given, orget_template()
if one name is given.
如果给定模板名称的可迭代对象,则使用select_template()
,如果给定一个名称,则使用get_template()
。Changelog 更新日志
New in version 2.3.
- Parameters: 参数:
template_name_or_list (str | Template | List[str | Template]) –
template_name_or_list (str | Template | List[str | Template]) – 模板名称或列表(字符串 | 模板 | 列表[字符串 | 模板])-parent (str | None) –
parent (str | None) – 父模板(字符串 | 无)-globals (MutableMapping[str, Any] | None) –
globals (MutableMapping[str, Any] | None) – 全局变量(可变映射[字符串, 任意类型] | 无)-
- Return type: 返回类型:
- from_string(source, globals=None, template_class=None)¶
Load a template from a source string without using
loader
.
从源字符串加载模板,而不使用loader
。- Parameters: 参数:
source (str | Template) – Jinja source to compile into a template.
source(str | 模板)- 要编译为模板的 Jinja 源代码。globals (MutableMapping[str, Any] | None) – Extend the environment
globals
with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items.
globals(MutableMapping[str, Any] | None)- 使用这些额外变量扩展环境globals
,以便在此模板的所有渲染中都可用。如果模板已经被加载和缓存,其全局变量将会更新为任何新项。template_class (Type[Template] | None) – Return an instance of this
Template
class.
template_class(Type[Template] | None)- 返回此Template
类的实例。
- Return type: 返回类型:
- class jinja2.Template(source, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, enable_async=False)¶
A compiled template that can be rendered.
可以呈现的已编译模板。Use the methods on
Environment
to create or load templates. The environment is used to configure how templates are compiled and behave.
使用Environment
上的方法来创建或加载模板。环境用于配置模板的编译和行为。It is also possible to create a template object directly. This is not usually recommended. The constructor takes most of the same arguments as
Environment
. All templates created with the same environment arguments share the same ephemeralEnvironment
instance behind the scenes.
也可以直接创建模板对象。这通常不被推荐。构造函数接受与Environment
相同的大部分参数。使用相同环境参数创建的所有模板在幕后共享同一个临时Environment
实例。A template object should be considered immutable. Modifications on the object are not supported.
模板对象应被视为不可变的。不支持对对象进行修改。- Parameters: 参数:
block_start_string (str) –
block_start_string(str)-block_end_string (str) –
block_end_string(str)-variable_start_string (str) –
variable_start_string (str) -variable_end_string (str) –
variable_end_string (str) -comment_start_string (str) –
comment_start_string (str) -comment_end_string (str) –
line_statement_prefix (str | None) –
line_comment_prefix (str | None) –
trim_blocks (bool) – trim_blocks(布尔值)–
lstrip_blocks (bool) – lstrip_blocks(布尔值)–
newline_sequence (te.Literal['\n', '\r\n', '\r']) –
newline_sequence(te.Literal['\n', '\r\n', '\r'])–keep_trailing_newline (bool) –
keep_trailing_newline(布尔值)-extensions (Sequence[str | Type[Extension]]) –
extensions(字符串序列 | 扩展类型)-optimized (bool) – optimized(布尔值)-
finalize (Callable[[...], Any] | None) –
完成(可调用[[...], 任意] | 无)-enable_async (bool) –
- Return type: 返回类型:
- globals¶ 全局变量 ¶
A dict of variables that are available every time the template is rendered, without needing to pass them during render. This should not be modified, as depending on how the template was loaded it may be shared with the environment and other templates.
模板渲染时每次都可用的变量字典,无需在渲染期间传递。请勿修改此字典,因为根据模板的加载方式,它可能与环境和其他模板共享。Defaults to
Environment.globals
unless extra values are passed toEnvironment.get_template()
.
默认为Environment.globals
,除非传递额外的值给Environment.get_template()
。Globals are only intended for data that is common to every render of the template. Specific data should be passed to
render()
.
全局变量仅用于模板的每次渲染中都通用的数据。特定数据应传递给render()
。See The Global Namespace.
查看全局命名空间。
- name¶
The loading name of the template. If the template was loaded from a string this is
None
.
模板的加载名称。如果模板是从字符串加载的,则为None
。
- filename¶ 文件名 ¶
The filename of the template on the file system if it was loaded from there. Otherwise this is
None
.
如果模板是从文件系统加载的,则为模板在文件系统上的文件名。否则为None
。
- render([context])¶
This method accepts the same arguments as the
dict
constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:
该方法接受与dict
构造函数相同的参数:字典、字典子类或一些关键字参数。如果没有给出参数,上下文将为空。这两个调用是相同的:template.render(knights='that say nih') template.render({'knights': 'that say nih'})
This will return the rendered template as a string.
这将返回渲染后的模板作为字符串。
- generate([context])¶ 生成([上下文]) ¶
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings.
对于非常大的模板,一次性渲染整个模板可能不太实用,但是逐个评估每个语句并逐个生成部分是很有用的。这种方法基本上就是这样做的,并返回一个生成器,以字符串形式逐个生成项。It accepts the same arguments as
render()
.
它接受与render()
相同的参数。
- stream([context])¶ 流([上下文]) ¶
Works exactly like
generate()
but returns aTemplateStream
.
功能与generate()
完全相同,但返回TemplateStream
。- Parameters: 参数:
- Return type: 返回类型:
-
async render_async([context])¶
异步渲染_async([context]) ¶ This works similar to
render()
but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.
这与render()
类似,但返回一个协程,当等待时返回整个渲染的模板字符串。这需要启用异步功能。Example usage: 示例用法:
await template.render_async(knights='that say nih; asynchronously')
-
async generate_async([context])¶
async generate_async([上下文])¶ An async version of
generate()
. Works very similarly but returns an async iterator instead.
generate()
的异步版本。工作方式非常相似,但返回一个异步迭代器。- Parameters: 参数:
- Return type: 返回类型:
AsyncIterator[str] AsyncIterator [str]
-
make_module(vars=None, shared=False, locals=None)¶
make_module(vars = None,shared = False,locals = None)¶ This method works like the
module
attribute when called without arguments but it will evaluate the template on every call rather than caching it. It’s also possible to provide a dict which is then used as context. The arguments are the same as for thenew_context()
method.
当没有参数调用时,此方法的工作方式类似于module
属性,但它会在每次调用时评估模板,而不是缓存它。还可以提供一个字典,然后将其用作上下文。参数与new_context()
方法相同。
-
property module: TemplateModule¶
属性模块: 模板模块 ¶ The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:
该模板作为模块。这在模板运行时用于导入,但如果想要从 Python 层访问导出的模板变量,也很有用:>>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> str(t.module) '23' >>> t.module.foo() == u'42' True
This attribute is not available if async mode is enabled.
如果启用了异步模式,则此属性不可用。
- class jinja2.environment.TemplateStream¶
A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one string is yielded.
模板流的工作方式与普通的 Python 生成器非常相似,但它可以缓冲多个项以减少总迭代次数。默认情况下,输出是无缓冲的,这意味着对于模板中的每个无缓冲指令,都会产生一个字符串。If buffering is enabled with a buffer size of 5, five items are combined into a new string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration.
如果启用了缓冲,并且缓冲区大小为 5,则将五个项目组合成一个新的字符串。这在通过 WSGI 向客户端流式传输大型模板并在每次迭代后刷新时非常有用。- dump(fp, encoding=None, errors='strict')¶
Dump the complete stream into a file or file-like object. Per default strings are written, if you want to encode before writing specify an
encoding
.
将完整的流转储到文件或类似文件的对象中。默认情况下,字符串会被写入,如果您想在写入之前进行编码,请指定一个encoding
。Example usage: 示例用法:
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
- disable_buffering()¶ 禁用缓冲() ¶
Disable the output buffering.
禁用输出缓冲。- Return type: 返回类型:
None
Autoescaping¶ 自动转义 ¶
Changelog 更新日志
Changed in version 2.4.
Jinja now comes with autoescaping support. As of Jinja 2.9 the
autoescape extension is removed and built-in. However autoescaping is
not yet enabled by default though this will most likely change in the
future. It’s recommended to configure a sensible default for
autoescaping. This makes it possible to enable and disable autoescaping
on a per-template basis (HTML versus text for instance).
Jinja 现在支持自动转义。自 Jinja 2.9 版本起,自动转义扩展已被移除并内置。然而,默认情况下尚未启用自动转义,尽管这很可能会在将来发生改变。建议为自动转义配置一个合理的默认值。这样可以在每个模板上启用或禁用自动转义(例如 HTML 与文本)。
- jinja2.select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False)¶
Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself.
根据模板的文件名智能地设置自动转义的初始值。如果您不想自己编写自定义函数,这是推荐的配置自动转义的方式。If you want to enable it for all templates created from strings or for all templates with
.html
and.xml
extensions:
如果您想为所有从字符串创建的模板或所有具有.html
和.xml
扩展名的模板启用它:from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, ))
Example configuration to turn it on at all times except if the template ends with
.txt
:
示例配置,始终打开,除非模板以.txt
结尾:from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, ))
The
enabled_extensions
is an iterable of all the extensions that autoescaping should be enabled for. Likewisedisabled_extensions
is a list of all templates it should be disabled for. If a template is loaded from a string then the default fromdefault_for_string
is used. If nothing matches then the initial value of autoescaping is set to the value ofdefault
.
enabled_extensions
是应启用自动转义的所有扩展的可迭代对象。同样,disabled_extensions
是应禁用自动转义的所有模板的列表。如果从字符串加载模板,则使用default_for_string
的默认值。如果没有匹配项,则自动转义的初始值设置为default
的值。For security reasons this function operates case insensitive.
出于安全原因,此功能不区分大小写操作。Changelog 更新日志
New in version 2.9.
- Parameters: 参数:
enabled_extensions (Collection[str]) –
enabled_extensions(Collection[str])-disabled_extensions (Collection[str]) –
disabled_extensions(Collection[str])-default_for_string (bool) –
default_for_string(bool)-default (bool) –
- Return type: 返回类型:
Here a recommended setup that enables autoescaping for templates ending
in '.html'
, '.htm'
and '.xml'
and disabling it by default
for all other extensions. You can use the select_autoescape()
function for this:
这里是一个推荐的设置,可以为以 '.html'
, '.htm'
和 '.xml'
结尾的模板启用自动转义,并默认情况下禁用所有其他扩展名。您可以使用 select_autoescape()
函数来实现这一点:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
loader=PackageLoader('mypackage'))
The select_autoescape()
function returns a function that
works roughly like this:
select_autoescape()
函数返回一个大致工作如下的函数:
def autoescape(template_name):
if template_name is None:
return False
if template_name.endswith(('.html', '.htm', '.xml'))
When implementing a guessing autoescape function, make sure you also
accept None
as valid template name. This will be passed when generating
templates from strings. You should always configure autoescaping as
defaults in the future might change.
当实现猜测自动转义函数时,请确保也接受 None
作为有效的模板名称。在从字符串生成模板时将传递此名称。您应该始终将自动转义配置为默认值,因为未来可能会更改。
Inside the templates the behaviour can be temporarily changed by using
the autoescape
block (see Autoescape Overrides).
在模板内部,可以通过使用 autoescape
块(参见自动转义覆盖)来临时更改行为。
Notes on Identifiers¶ 标识符注释 ¶
Jinja uses Python naming rules. Valid identifiers can be any combination
of characters accepted by Python.
Jinja 使用 Python 命名规则。有效的标识符可以是 Python 接受的任何字符组合。
Filters and tests are looked up in separate namespaces and have slightly
modified identifier syntax. Filters and tests may contain dots to group
filters and tests by topic. For example it’s perfectly valid to add a
function into the filter dict and call it to.str
. The regular
expression for filter and test identifiers is
[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*
.
过滤器和测试在不同的命名空间中查找,并具有稍微修改的标识符语法。过滤器和测试可以包含点来按主题分组过滤器和测试。例如,将函数添加到过滤器字典中并调用它 to.str
是完全有效的。过滤器和测试标识符的正则表达式是 [a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*
。
Undefined Types¶ 未定义的类型 ¶
These classes can be used as undefined types. The Environment
constructor takes an undefined
parameter that can be one of those classes
or a custom subclass of Undefined
. Whenever the template engine is
unable to look up a name or access an attribute one of those objects is
created and returned. Some operations on undefined values are then allowed,
others fail.
这些类可以用作未定义的类型。 Environment
构造函数接受一个 undefined
参数,可以是这些类之一,也可以是 Undefined
的自定义子类。每当模板引擎无法查找名称或访问属性时,将创建并返回其中一个对象。然后允许对未定义值进行某些操作,而其他操作将失败。
The closest to regular Python behavior is the StrictUndefined
which
disallows all operations beside testing if it’s an undefined object.
最接近常规 Python 行为的是 StrictUndefined
,它除了测试是否为未定义对象外,不允许进行任何操作。
- class jinja2.Undefined¶
The default undefined type. This undefined type can be printed and iterated over, but every other access will raise an
UndefinedError
:
默认的未定义类型。此未定义类型可以打印和迭代,但是其他任何访问都会引发UndefinedError
:>>> foo = Undefined(name='foo') >>> str(foo) '' >>> not foo True >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined
- Parameters: 参数:
hint (str | None) –
提示(str | None)-obj (Any) – obj(任意类型)-
name (str | None) –
名称 (str | None) -exc (Type[TemplateRuntimeError]) –
- _undefined_hint¶ _未定义的提示 ¶
Either
None
or a string with the error message for the undefined object.
要么None
,要么是未定义对象的错误消息字符串。
- _undefined_obj¶ _未定义的对象 ¶
Either
None
or the owner object that caused the undefined object to be created (for example because an attribute does not exist).
要么None
,要么是导致未定义对象创建的所有者对象(例如因为属性不存在)。
- _undefined_name¶ _undefined_name
The name for the undefined variable / attribute or just
None
if no such information exists.
如果未定义的变量/属性没有相关信息,则为None
。
- _undefined_exception¶
The exception that the undefined object wants to raise. This is usually one of
UndefinedError
orSecurityError
.
未定义的对象要引发的异常。通常为UndefinedError
或SecurityError
之一。
- _fail_with_undefined_error(\*args, \**kwargs)¶
When called with any arguments this method raises
_undefined_exception
with an error message generated from the undefined hints stored on the undefined object.
当使用任何参数调用此方法时,它会引发一个错误消息,该消息是从存储在未定义对象上的未定义提示生成的。
-
class jinja2.ChainableUndefined¶
类 jinja2.ChainableUndefined An undefined that is chainable, where both
__getattr__
and__getitem__
return itself rather than raising anUndefinedError
.
一个可链式调用的未定义对象,其中__getattr__
和__getitem__
都返回自身,而不是引发UndefinedError
。>>> foo = ChainableUndefined(name='foo') >>> str(foo.bar['baz']) '' >>> foo.bar['baz'] + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined
Changelog 更新日志
New in version 2.11.0.
- Parameters: 参数:
hint (str | None) –
提示 (str | None) –obj (Any) – 对象 (Any) –
name (str | None) –
名称 (str | None) -exc (Type[TemplateRuntimeError]) –
exc(Type[TemplateRuntimeError])-
-
class jinja2.DebugUndefined¶
类 jinja2.DebugUndefined ¶ An undefined that returns the debug info when printed.
一个未定义的对象,在打印时返回调试信息。>>> foo = DebugUndefined(name='foo') >>> str(foo) '{{ foo }}' >>> not foo True >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined
- Parameters: 参数:
hint (str | None) –
提示 (str | 无) –obj (Any) – 对象 (任意) –
name (str | None) –
名称 (str | None) -exc (Type[TemplateRuntimeError]) –
异常 (TemplateRuntimeError 类型) –
-
class jinja2.StrictUndefined¶
类 jinja2.StrictUndefined ¶ An undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it’s defined using the
defined
test.
一个未定义的对象,在打印和迭代以及布尔测试和各种比较中都会发出警告。换句话说:除了使用defined
测试检查是否定义之外,你什么都不能做。>>> foo = StrictUndefined(name='foo') >>> str(foo) Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined >>> not foo Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined >>> foo + 42 Traceback (most recent call last): ... jinja2.exceptions.UndefinedError: 'foo' is undefined
- Parameters: 参数:
hint (str | None) –
提示(字符串 | 无)-obj (Any) – 对象(任意类型)-
name (str | None) –
名称 (str | None) -exc (Type[TemplateRuntimeError]) –
exc(TemplateRuntimeError 类型)-
There is also a factory function that can decorate undefined objects to
implement logging on failures:
还有一个工厂函数,可以装饰未定义的对象,以实现在失败时记录日志:
- jinja2.make_logging_undefined(logger=None, base=Undefined)¶
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.
给定一个日志记录器对象,将返回一个新的未定义类,该类将记录某些失败。它将记录迭代和打印。如果未提供日志记录器,则创建默认日志记录器。Example: 示例:
logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined )
Changelog 更改日志
New in version 2.8.
- Parameters: 参数:
logger (logging.Logger | None) – the logger to use. If not provided, a default logger is created.
logger (logging.Logger | None) – 要使用的记录器。如果未提供,则创建一个默认记录器。base (Type[Undefined]) – the base class to add logging functionality to. This defaults to
Undefined
.
base(Type[Undefined])- 要添加日志功能的基类。默认为Undefined
。
- Return type: 返回类型:
Undefined objects are created by calling undefined
.
通过调用 undefined
来创建未定义的对象。
Implementation 实施
Undefined
is implemented by overriding the special
__underscore__
methods. For example the default
Undefined
class implements __str__
to returns an empty
string, while __int__
and others fail with an exception. To
allow conversion to int by returning 0
you can implement your
own subclass.
Undefined
通过覆盖特殊的 __underscore__
方法来实现。例如,默认的 Undefined
类实现了 __str__
来返回一个空字符串,而 __int__
和其他类则会抛出异常。为了通过返回 0
来允许转换为整数,您可以实现自己的子类。
class NullUndefined(Undefined):
def __int__(self):
return 0
def __float__(self):
return 0.0
To disallow a method, override it and raise
_undefined_exception
. Because this is very
common there is the helper method
_fail_with_undefined_error()
that raises the error
with the correct information. Here’s a class that works like the
regular Undefined
but fails on iteration:
要禁止某个方法,请重写它并引发 _undefined_exception
。由于这是非常常见的操作,因此有一个辅助方法 _fail_with_undefined_error()
,它会使用正确的信息引发错误。下面是一个类,它的工作方式类似于常规的 Undefined
,但在迭代时会失败:
class NonIterableUndefined(Undefined):
def __iter__(self):
self._fail_with_undefined_error()
The Context¶ 上下文 ¶
-
class jinja2.runtime.Context¶
类 jinja2.runtime.Context ¶ The template context holds the variables of a template. It stores the values passed to the template and also the names the template exports. Creating instances is neither supported nor useful as it’s created automatically at various stages of the template evaluation and should not be created by hand.
模板上下文保存模板的变量。它存储传递给模板的值,以及模板导出的名称。创建实例既不受支持也没有用处,因为它会在模板评估的各个阶段自动创建,不应该手动创建。The context is immutable. Modifications on
parent
must not happen and modifications onvars
are allowed from generated template code only. Template filters and global functions marked aspass_context()
get the active context passed as first argument and are allowed to access the context read-only.
上下文是不可变的。parent
上的修改不得发生,只允许从生成的模板代码对vars
进行修改。模板过滤器和标记为pass_context()
的全局函数会将活动上下文作为第一个参数传递,并且只允许以只读方式访问上下文。The template context supports read only dict operations (
get
,keys
,values
,items
,iterkeys
,itervalues
,iteritems
,__getitem__
,__contains__
). Additionally there is aresolve()
method that doesn’t fail with aKeyError
but returns anUndefined
object for missing variables.
模板上下文支持只读字典操作(get
,keys
,values
,items
,iterkeys
,itervalues
,iteritems
,__getitem__
,__contains__
)。此外,还有一个resolve()
方法,不会因为KeyError
而失败,而是对于缺少的变量返回一个Undefined
对象。- Parameters: 参数:
- parent¶ 父级 ¶
A dict of read only, global variables the template looks up. These can either come from another
Context
, from theEnvironment.globals
orTemplate.globals
or points to a dict created by combining the globals with the variables passed to the render function. It must not be altered.
模板查找的只读全局变量字典。这些变量可以来自另一个Context
,来自Environment.globals
或Template.globals
,或者指向一个由全局变量与传递给渲染函数的变量组合而成的字典。它不得被更改。
- vars¶ 变量 ¶
The template local variables. This list contains environment and context functions from the
parent
scope as well as local modifications and exported variables from the template. The template will modify this dict during template evaluation but filters and context functions are not allowed to modify it.
模板本地变量。此列表包含parent
范围内的环境和上下文函数,以及模板中的本地修改和导出变量。模板在模板评估期间将修改此字典,但过滤器和上下文函数不允许修改它。
- environment¶ 环境 ¶
The environment that loaded the template.
加载模板的环境。
- exported_vars¶ 导出的变量 ¶
This set contains all the names the template exports. The values for the names are in the
vars
dict. In order to get a copy of the exported variables as dict,get_exported()
can be used.
此集合包含模板导出的所有名称。名称的值在vars
字典中。为了获得导出变量的副本作为字典,可以使用get_exported()
。
- name¶ 名称 ¶
The load name of the template owning this context.
拥有此上下文的模板的负载名称。
- blocks¶
A dict with the current mapping of blocks in the template. The keys in this dict are the names of the blocks, and the values a list of blocks registered. The last item in each list is the current active block (latest in the inheritance chain).
模板中当前块的映射字典。该字典的键是块的名称,值是注册的块列表。每个列表中的最后一项是当前活动块(继承链中的最新项)。
- eval_ctx¶
The current Evaluation Context.
当前评估上下文。
- 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 has
pass_context()
orpass_environment()
.
使用提供的参数和关键字参数调用可调用对象,但如果可调用对象具有pass_context()
或pass_environment()
,则将活动上下文或环境注入为第一个参数。
- get(key, default=None)¶
Look up a variable by name, or return a default if the key is not found.
根据名称查找变量,如果未找到键,则返回默认值。
- resolve(key)¶
Look up a variable by name, or return an
Undefined
object if the key is not found.
通过名称查找变量,如果未找到键,则返回Undefined
对象。If you need to add custom behavior, override
resolve_or_missing()
, not this method. The various lookup functions use that method, not this one.
如果您需要添加自定义行为,请覆盖resolve_or_missing()
,而不是这个方法。各种查找函数使用该方法,而不是这个。
- resolve_or_missing(key)¶
Look up a variable by name, or return a
missing
sentinel if the key is not found.
按名称查找变量,如果未找到键,则返回missing
标记。Override this method to add custom lookup behavior.
resolve()
,get()
, and__getitem__()
use this method. Don’t call this method directly.
重写此方法以添加自定义查找行为。resolve()
,get()
和__getitem__()
使用此方法。不要直接调用此方法。
- get_exported()¶
Get a new dict with the exported variables.
获取一个包含导出变量的新字典。
The context is immutable, it prevents modifications, and if it is
modified somehow despite that those changes may not show up. For
performance, Jinja does not use the context as data storage for, only as
a primary data source. Variables that the template does not define are
looked up in the context, but variables the template does define are
stored locally.
上下文是不可变的,它防止修改,即使在某种情况下被修改,这些更改可能不会显示出来。为了性能,Jinja 不将上下文用作数据存储,而只用作主要数据源。模板未定义的变量在上下文中查找,但模板定义的变量存储在本地。
Instead of modifying the context directly, a function should return
a value that can be assigned to a variable within the template itself.
一个函数应该返回一个可以在模板内部赋值给变量的值,而不是直接修改上下文。
{% set comments = get_latest_comments() %}
Loaders¶ 加载器 ¶
Loaders are responsible for loading templates from a resource such as the
file system. The environment will keep the compiled modules in memory like
Python’s sys.modules
. Unlike sys.modules
however this cache is limited in
size by default and templates are automatically reloaded.
All loaders are subclasses of BaseLoader
. If you want to create your
own loader, subclass BaseLoader
and override get_source
.
加载器负责从资源(如文件系统)加载模板。环境将像 Python 的 sys.modules
一样将编译的模块保存在内存中。但是,与 sys.modules
不同的是,默认情况下,此缓存的大小是有限的,并且模板会自动重新加载。所有加载器都是 BaseLoader
的子类。如果要创建自己的加载器,请子类化 BaseLoader
并覆盖 get_source
。
-
class jinja2.BaseLoader¶
类 jinja2.BaseLoader ¶ Baseclass for all loaders. Subclass this and override
get_source
to implement a custom loading mechanism. The environment provides aget_template
method that calls the loader’sload
method to get theTemplate
object.
用于所有加载器的基类。子类化此类并覆盖get_source
以实现自定义加载机制。环境提供了一个get_template
方法,该方法调用加载器的load
方法以获取Template
对象。A very basic example for a loader that looks up templates on the file system could look like this:
一个非常基本的示例,用于在文件系统上查找模板的加载器可能如下所示:from jinja2 import BaseLoader, TemplateNotFound from os.path import join, exists, getmtime class MyLoader(BaseLoader): def __init__(self, path): self.path = path def get_source(self, environment, template): path = join(self.path, template) if not exists(path): raise TemplateNotFound(template) mtime = getmtime(path) with open(path) as f: source = f.read() return source, path, lambda: mtime == getmtime(path)
- 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 aTemplateNotFound
error if it can’t locate the template.
获取模板的源代码、文件名和重新加载助手。它接收环境和模板名称,并返回一个形式为(source, filename, uptodate)
的元组,如果无法找到模板,则引发TemplateNotFound
错误。The source part of the returned tuple must be the source of the template as a string. 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.
返回的元组的源部分必须是模板的源字符串。如果模板是从文件系统加载的,则文件名应该是文件在文件系统中的名称,否则为None
。如果没有使用加载器扩展名,Python 将使用文件名进行回溯。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 returnsFalse
the template will be reloaded.
元组中的最后一项是uptodate
函数。如果启用了自动重新加载,则始终调用该函数以检查模板是否更改。不传递任何参数,因此函数必须在某个地方存储旧状态(例如在闭包中)。如果返回False
,则重新加载模板。
- 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 asPrefixLoader
orChoiceLoader
) will not call this method butget_source
directly.
加载模板。此方法在缓存中查找模板或通过调用get_source()
来加载一个模板。子类不应覆盖此方法,因为对其他加载器集合(如PrefixLoader
或ChoiceLoader
)进行操作的加载器不会调用此方法,而是直接调用get_source
。- Parameters: 参数:
environment (Environment) –
name (str) – 名称(str)-
globals (MutableMapping[str, Any] | None) –
全局变量(MutableMapping[str, Any] | None)-
- Return type: 返回类型:
Here a list of the builtin loaders Jinja provides:
这里是 Jinja 提供的内置加载器列表:
- class jinja2.FileSystemLoader(searchpath, encoding='utf-8', followlinks=False)¶
Load templates from a directory in the file system.
从文件系统中的目录加载模板。The path can be relative or absolute. Relative paths are relative to the current working directory.
路径可以是相对路径或绝对路径。相对路径是相对于当前工作目录的。loader = FileSystemLoader("templates")
A list of paths can be given. The directories will be searched in order, stopping at the first matching template.
可以给出路径列表。目录将按顺序进行搜索,停在第一个匹配的模板处。loader = FileSystemLoader(["/override/templates", "/default/templates"])
- Parameters: 参数:
searchpath (str | os.PathLike[str] | Sequence[str | os.PathLike[str]]) – A path, or list of paths, to the directory that contains the templates.
searchpath(str | os.PathLike[str] | Sequence[str | os.PathLike[str]])- 包含模板的目录的路径或路径列表。encoding (str) – Use this encoding to read the text from template files.
encoding(str)- 使用此编码来读取模板文件中的文本。followlinks (bool) – Follow symbolic links in the path.
followlinks(bool)- 遵循路径中的符号链接。
Changelog 更新日志
Changed in version 2.8: Added the
followlinks
parameter.
- class jinja2.PackageLoader(package_name, package_path='templates', encoding='utf-8')¶
Load templates from a directory in a Python package.
从 Python 包中的目录加载模板。- Parameters: 参数:
package_name (str) – Import name of the package that contains the template directory.
package_name(str)- 包含模板目录的包的导入名称。package_path (str) – Directory within the imported package that contains the templates.
package_path(str)- 导入包中包含模板的目录。encoding (str) – Encoding of template files.
encoding(str)- 模板文件的编码。
The following example looks up templates in the
pages
directory within theproject.ui
package.
以下示例查找project.ui
包中的pages
目录中的模板。loader = PackageLoader("project.ui", "pages")
Only packages installed as directories (standard pip behavior) or zip/egg files (less common) are supported. The Python API for introspecting data in packages is too limited to support other installation methods the way this loader requires.
仅支持作为目录(标准 pip 行为)安装的软件包或 zip/egg 文件(较不常见)。Python 用于检查软件包中数据的 API 过于有限,无法支持此加载程序所需的其他安装方法。There is limited support for PEP 420 namespace packages. The template directory is assumed to only be in one namespace contributor. Zip files contributing to a namespace are not supported.
对于 PEP 420 命名空间包的支持有限。假定模板目录仅位于一个命名空间贡献者中。不支持为命名空间贡献的 zip 文件。Changelog 更新日志
Changed in version 3.0: No longer uses
setuptools
as a dependency.Changed in version 3.0: Limited PEP 420 namespace package support.
- class jinja2.DictLoader(mapping)¶
Loads a template from a Python dict mapping template names to template source. This loader is useful for unittesting:
从 Python 字典映射模板名称到模板源代码加载模板。此加载器适用于单元测试:>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
因为自动重新加载很少有用,所以默认情况下禁用该功能。
-
class jinja2.FunctionLoader(load_func)¶
类 jinja2.FunctionLoader(load_func) ¶ A loader that is passed a function which does the loading. The function receives the name of the template and has to return either a string with the template source, a tuple in the form
(source, filename, uptodatefunc)
orNone
if the template does not exist.
传递一个执行加载操作的函数的加载器。该函数接收模板的名称,并且必须返回模板源代码的字符串,或者如果模板不存在,则返回形如(source, filename, uptodatefunc)
或None
的元组。>>> def load_template(name): ... if name == 'index.html': ... return '...' ... >>> loader = FunctionLoader(load_template)
The
uptodatefunc
is a function that is called if autoreload is enabled and has to returnTrue
if the template is still up to date. For more details have a look atBaseLoader.get_source()
which has the same return value.
如果启用了自动重新加载,将调用uptodatefunc
函数,并且必须返回True
以表示模板是否仍然是最新的。有关更多详细信息,请参阅具有相同返回值的BaseLoader.get_source()
。
-
class jinja2.PrefixLoader(mapping, delimiter='/')¶
类 jinja2.PrefixLoader(映射,分隔符='/') ¶ A loader that is passed a dict of loaders where each loader is bound to a prefix. The prefix is delimited from the template by a slash per default, which can be changed by setting the
delimiter
argument to something else:
一个加载器,它接收一个加载器字典,其中每个加载器都绑定到一个前缀。默认情况下,前缀与模板之间由斜杠分隔,可以通过将delimiter
参数设置为其他值来更改这一点:loader = PrefixLoader({ 'app1': PackageLoader('mypackage.app1'), 'app2': PackageLoader('mypackage.app2') })
By loading
'app1/index.html'
the file from the app1 package is loaded, by loading'app2/index.html'
the file from the second.
通过加载'app1/index.html'
,从 app1 包中加载文件;通过加载'app2/index.html'
,从第二个包中加载文件。- Parameters: 参数:
mapping (Mapping[str, BaseLoader]) –
映射(Mapping[str, BaseLoader])-delimiter (str) – 分隔符(str)-
- class jinja2.ChoiceLoader(loaders)¶
This loader works like the
PrefixLoader
just that no prefix is specified. If a template could not be found by one loader the next one is tried.
这个加载器的工作方式类似于PrefixLoader
,只是没有指定前缀。如果一个模板在一个加载器中找不到,就会尝试下一个加载器。>>> loader = ChoiceLoader([ ... FileSystemLoader('/path/to/user/templates'), ... FileSystemLoader('/path/to/system/templates') ... ])
This is useful if you want to allow users to override builtin templates from a different location.
如果您希望允许用户从不同位置覆盖内置模板,则这非常有用。- Parameters: 参数:
loaders (Sequence[BaseLoader]) –
加载器(Sequence[BaseLoader])-
-
class jinja2.ModuleLoader(path)¶
类 jinja2.ModuleLoader(path) ¶ This loader loads templates from precompiled templates.
此加载器从预编译模板中加载模板。Example usage: 用法示例:
>>> loader = ChoiceLoader([ ... ModuleLoader('/path/to/compiled/templates'), ... FileSystemLoader('/path/to/templates') ... ])
Templates can be precompiled with
Environment.compile_templates()
.
模板可以使用Environment.compile_templates()
进行预编译。- Parameters: 参数:
path (str | os.PathLike[str] | Sequence[str | os.PathLike[str]]) –
路径(str | os.PathLike[str] | Sequence[str | os.PathLike[str]])-
Bytecode Cache¶ 字节码缓存 ¶
Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
it possible to store the generated bytecode on the file system or a different
location to avoid parsing the templates on first use.
Jinja 2.1 及更高版本支持外部字节码缓存。字节码缓存使得可以将生成的字节码存储在文件系统或其他位置,以避免在首次使用时解析模板。
This is especially useful if you have a web application that is initialized on
the first request and Jinja compiles many templates at once which slows down
the application.
如果您有一个在第一次请求时初始化的 Web 应用程序,并且 Jinja 一次编译许多模板,这对您非常有用,因为这会减慢应用程序的速度。
To use a bytecode cache, instantiate it and pass it to the Environment
.
要使用字节码缓存,请实例化它并将其传递给 Environment
。
-
class jinja2.BytecodeCache¶
类 jinja2.BytecodeCache ¶ To implement your own bytecode cache you have to subclass this class and override
load_bytecode()
anddump_bytecode()
. Both of these methods are passed aBucket
.
要实现自己的字节码缓存,您必须继承此类并覆盖load_bytecode()
和dump_bytecode()
。这两个方法都会传递一个Bucket
。A very basic bytecode cache that saves the bytecode on the file system:
一个非常基本的字节码缓存,将字节码保存在文件系统上:from os import path class MyCache(BytecodeCache): def __init__(self, directory): self.directory = directory def load_bytecode(self, bucket): filename = path.join(self.directory, bucket.key) if path.exists(filename): with open(filename, 'rb') as f: bucket.load_bytecode(f) def dump_bytecode(self, bucket): filename = path.join(self.directory, bucket.key) with open(filename, 'wb') as f: bucket.write_bytecode(f)
A more advanced version of a filesystem based bytecode cache is part of Jinja.
文件系统基于字节码缓存的更高级版本是 Jinja 的一部分。- load_bytecode(bucket)¶
Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.
子类必须重写此方法,将字节码加载到存储桶中。如果它们无法在存储桶的缓存中找到代码,则不得执行任何操作。- Parameters: 参数:
bucket (Bucket) – 存储桶(Bucket)-
- Return type: 返回类型:
None 无
- dump_bytecode(bucket)¶
Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.
子类必须重写此方法,将存储桶中的字节码写回缓存。如果无法执行此操作,则不能静默失败,而是必须引发异常。- Parameters: 参数:
bucket (Bucket) – 存储桶(Bucket)-
- Return type: 返回类型:
None 无
- clear()¶
Clears the cache. This method is not used by Jinja but should be implemented to allow applications to clear the bytecode cache used by a particular environment.
清除缓存。这个方法不被 Jinja 使用,但应该被实现,以允许应用程序清除特定环境使用的字节码缓存。- Return type: 返回类型:
None 无
- class jinja2.bccache.Bucket(environment, key, checksum)¶
Buckets are used to store the bytecode for one template. It’s created and initialized by the bytecode cache and passed to the loading functions.
Bucket 用于存储一个模板的字节码。它由字节码缓存创建和初始化,并传递给加载函数。The buckets get an internal checksum from the cache assigned and use this to automatically reject outdated cache material. Individual bytecode cache subclasses don’t have to care about cache invalidation.
存储桶从分配的缓存中获取内部校验和,并使用此校验和自动拒绝过时的缓存材料。个别的字节码缓存子类不需要关心缓存失效。- Parameters: 参数:
environment (Environment) –
环境(Environment)-key (str) – 键(str)-
checksum (str) – 校验和(str)-
- environment¶ 环境 ¶
The
Environment
that created the bucket.
创建存储桶的Environment
。
- key¶ 键 ¶
The unique cache key for this bucket
此存储桶的唯一缓存键
- code¶
The bytecode if it’s loaded, otherwise
None
.
如果加载了字节码,则为字节码,否则为None
。
- reset()¶
Resets the bucket (unloads the bytecode).
重置桶(卸载字节码)。- Return type: 返回类型:
None 无
- load_bytecode(f)¶
Loads bytecode from a file or file like object.
从文件或类似文件对象加载字节码。- Parameters: 参数:
f (BinaryIO) – f(BinaryIO)-
- Return type: 返回类型:
None 无
- write_bytecode(f)¶
Dump the bytecode into the file or file like object passed.
将字节码转储到传递的文件或类似文件的对象中。
Builtin bytecode caches:
内置字节码缓存:
-
class jinja2.FileSystemBytecodeCache(directory=None, pattern='__jinja2_%s.cache')¶
类 jinja2.FileSystemBytecodeCache(directory = None,pattern ='__jinja2%s.cache')¶ A bytecode cache that stores bytecode on the filesystem. It accepts two arguments: The directory where the cache items are stored and a pattern string that is used to build the filename.
一个在文件系统上存储字节码的字节码缓存。它接受两个参数:存储缓存项的目录和用于构建文件名的模式字符串。If no directory is specified a default cache directory is selected. On Windows the user’s temp directory is used, on UNIX systems a directory is created for the user in the system temp directory.
如果未指定目录,则会选择默认的缓存目录。在 Windows 上,使用用户的临时目录,在 UNIX 系统上,会在系统临时目录为用户创建一个目录。The pattern can be used to have multiple separate caches operate on the same directory. The default pattern is
'__jinja2_%s.cache'
.%s
is replaced with the cache key.
该模式可用于使多个独立缓存在同一目录上运行。默认模式为'__jinja2_%s.cache'
。%s
将被缓存键替换。>>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
This bytecode cache supports clearing of the cache using the clear method.
此字节码缓存支持使用 clear 方法清除缓存。
- class jinja2.MemcachedBytecodeCache(client, prefix='jinja2/bytecode/', timeout=None, ignore_memcache_errors=True)¶
This class implements a bytecode cache that uses a memcache cache for storing the information. It does not enforce a specific memcache library (tummy’s memcache or cmemcache) but will accept any class that provides the minimal interface required.
此类实现了一个字节码缓存,使用 memcache 缓存来存储信息。它不强制使用特定的 memcache 库(如 tummy 的 memcache 或 cmemcache),但会接受任何提供所需最小接口的类。Libraries compatible with this class:
兼容此类的库:(Unfortunately the django cache interface is not compatible because it does not support storing binary data, only text. You can however pass the underlying cache client to the bytecode cache which is available as
django.core.cache.cache._client
.)
(不幸的是,Django 缓存接口不兼容,因为它不支持存储二进制数据,只支持文本。但是,您可以将底层缓存客户端传递给字节码缓存,该客户端可用作django.core.cache.cache._client
。)The minimal interface for the client passed to the constructor is this:
传递给构造函数的客户端的最小接口是:- Parameters: 参数:
- class MinimalClientInterface¶
- set(key, value[, timeout])¶
Stores the bytecode in the cache.
value
is a string andtimeout
the timeout of the key. If timeout is not provided a default timeout or no timeout should be assumed, if it’s provided it’s an integer with the number of seconds the cache item should exist.
将字节码存储在缓存中。value
是一个字符串,timeout
是键的超时时间。如果未提供超时时间,则应假定默认超时时间或无超时时间;如果提供了超时时间,则应为一个整数,表示缓存项应存在的秒数。
- get(key)¶
Returns the value for the cache key. If the item does not exist in the cache the return value must be
None
.
返回缓存键的值。如果缓存中不存在该项,则返回值必须为None
。
The other arguments to the constructor are the prefix for all keys that is added before the actual cache key and the timeout for the bytecode in the cache system. We recommend a high (or no) timeout.
构造函数的其他参数是添加在实际缓存键之前的所有键的前缀和缓存系统中字节码的超时时间。我们建议设置较高的超时时间(或不设置超时时间)。This bytecode cache does not support clearing of used items in the cache. The clear method is a no-operation function.
此字节码缓存不支持清除缓存中的已使用项目。clear 方法是一个无操作函数。Changelog 更新日志
New in version 2.7: Added support for ignoring memcache errors through the
ignore_memcache_errors
parameter.
Async Support¶ 异步支持 ¶
Changelog 更新日志
New in version 2.9.
Jinja supports the Python async
and await
syntax. For the
template designer, this support (when enabled) is entirely transparent,
templates continue to look exactly the same. However, developers should
be aware of the implementation as it affects what types of APIs you can
use.
Jinja 支持 Python async
和 await
语法。对于模板设计师来说,这种支持(在启用时)是完全透明的,模板看起来仍然完全一样。但是,开发人员应该意识到它的实现方式,因为它会影响您可以使用的 API 类型。
By default, async support is disabled. Enabling it will cause the
environment to compile different code behind the scenes in order to
handle async and sync code in an asyncio event loop. This has the
following implications:
默认情况下,异步支持被禁用。启用它将导致环境在幕后编译不同的代码,以处理异步和同步代码在 asyncio 事件循环中。这有以下影响:
Template rendering requires an event loop to be available to the current thread.
asyncio.get_running_loop()
must return an event loop.
模板渲染需要当前线程可用的事件循环。asyncio.get_running_loop()
必须返回一个事件循环。The compiled code uses
await
for functions and attributes, and usesasync for
loops. In order to support using both async and sync functions in this context, a small wrapper is placed around all calls and access, which adds overhead compared to purely async code.
编译后的代码使用await
表示函数和属性,并使用async for
循环。为了支持在这种情况下同时使用异步和同步函数,会在所有调用和访问周围放置一个小包装器,这会增加与纯异步代码相比的开销。Sync methods and filters become wrappers around their corresponding async implementations where needed. For example,
render
invokesasync_render
, and|map
supports async iterables.
在必要时,同步方法和过滤器将成为它们对应的异步实现的包装器。例如,render
调用async_render
,|map
支持异步可迭代对象。
Awaitable objects can be returned from functions in templates and any
function call in a template will automatically await the result. The
await
you would normally add in Python is implied. For example, you
can provide a method that asynchronously loads data from a database, and
from the template designer’s point of view it can be called like any
other function.
模板中的函数可以返回可等待对象,并且模板中的任何函数调用都将自动等待结果。在 Python 中通常需要添加的 await
是隐含的。例如,您可以提供一个从数据库异步加载数据的方法,从模板设计师的角度来看,它可以像任何其他函数一样被调用。
Policies¶ 策略 ¶
Starting with Jinja 2.9 policies can be configured on the environment
which can slightly influence how filters and other template constructs
behave. They can be configured with the
policies
attribute.
从 Jinja 2.9 开始,可以在环境上配置策略,这些策略可以在一定程度上影响过滤器和其他模板结构的行为。它们可以通过 policies
属性进行配置。
Example: 例如:
env.policies['urlize.rel'] = 'nofollow noopener'
truncate.leeway
:Configures the leeway default for the
truncate
filter. Leeway as introduced in 2.9 but to restore compatibility with older templates it can be configured to0
to get the old behavior back. The default is5
.
配置truncate
过滤器的默认容差。容差在 2.9 中引入,但为了恢复与旧模板的兼容性,可以将其配置为0
以恢复旧行为。默认值为5
。urlize.rel
:A string that defines the items for the
rel
attribute of generated links with theurlize
filter. These items are always added. The default isnoopener
.
一个字符串,定义了使用urlize
过滤器生成链接的rel
属性的项目。这些项目始终会被添加。默认值为noopener
。urlize.target
:The default target that is issued for links from the
urlize
filter if no other target is defined by the call explicitly.
如果在调用中没有明确定义其他目标,则为来自urlize
过滤器的链接发出的默认目标。urlize.extra_schemes
:Recognize URLs that start with these schemes in addition to the default
http://
,https://
, andmailto:
.
除了默认的http://
、https://
和mailto:
之外,识别以这些方案开头的 URL。json.dumps_function
:If this is set to a value other than
None
then thetojson
filter will dump with this function instead of the default one. Note that this function should accept arbitrary extra arguments which might be passed in the future from the filter. Currently the only argument that might be passed isindent
. The default dump function isjson.dumps
.
如果将其设置为非None
的值,则tojson
过滤器将使用此函数而不是默认函数进行转储。请注意,此函数应接受可能从过滤器中传递的未来任意额外参数。目前可能传递的唯一参数是indent
。默认转储函数为json.dumps
。json.dumps_kwargs
:Keyword arguments to be passed to the dump function. The default is
{'sort_keys': True}
.
传递给转储函数的关键字参数。默认值为{'sort_keys': True}
。
ext.i18n.trimmed
:If this is set to
True
,{% trans %}
blocks of the i18n Extension will always unify linebreaks and surrounding whitespace as if thetrimmed
modifier was used.
如果设置为True
,i18n 扩展的{% trans %}
块将始终将换行符和周围的空格统一为使用trimmed
修饰符的方式。
Utilities¶ 实用工具 ¶
These helper functions and classes are useful if you add custom filters or
functions to a Jinja environment.
如果您向 Jinja 环境添加自定义过滤器或函数,则这些辅助函数和类非常有用。
- jinja2.pass_context(f)¶
Pass the
Context
as the first argument to the decorated function when called while rendering a template.
在渲染模板时,将Context
作为装饰函数的第一个参数传递。Can be used on functions, filters, and tests.
可用于函数、过滤器和测试。If only
Context.eval_context
is needed, usepass_eval_context()
. If onlyContext.environment
is needed, usepass_environment()
.
如果只需要Context.eval_context
,请使用pass_eval_context()
。如果只需要Context.environment
,请使用pass_environment()
。Changelog 更新日志
New in version 3.0.0: Replaces
contextfunction
andcontextfilter
.- Parameters: 参数:
f (F) –
- Return type: 返回类型
F
- jinja2.pass_eval_context(f)¶
Pass the
EvalContext
as the first argument to the decorated function when called while rendering a template. See Evaluation Context.
在渲染模板时,将EvalContext
作为第一个参数传递给装饰函数。参见评估上下文。Can be used on functions, filters, and tests.
可用于函数、过滤器和测试。If only
EvalContext.environment
is needed, usepass_environment()
.
如果只需要EvalContext.environment
,请使用pass_environment()
。Changelog 更新日志
New in version 3.0.0: Replaces
evalcontextfunction
andevalcontextfilter
.- Parameters: 参数:
f (F) – f(F)-
- Return type: 返回类型:
F
- jinja2.pass_environment(f)¶
Pass the
Environment
as the first argument to the decorated function when called while rendering a template.
在渲染模板时,将Environment
作为装饰函数的第一个参数传递。Can be used on functions, filters, and tests.
可用于函数、过滤器和测试。Changelog 更改日志
New in version 3.0.0: Replaces
environmentfunction
andenvironmentfilter
.- Parameters: 参数:
f (F) – f(F)-
- Return type: 返回类型:
F
- jinja2.clear_caches()¶
Jinja keeps internal caches for environments and lexers. These are used so that Jinja doesn’t have to recreate environments and lexers all the time. Normally you don’t have to care about that but if you are measuring memory consumption you may want to clean the caches.
Jinja 为环境和词法分析器保留了内部缓存。这些缓存用于避免 Jinja 一直重新创建环境和词法分析器。通常情况下,您不需要关心这一点,但如果您正在测量内存消耗,您可能希望清除缓存。- Return type: 返回类型:
None 无
- jinja2.is_undefined(obj)¶
Check if the object passed is undefined. This does nothing more than performing an instance check against
Undefined
but looks nicer. This can be used for custom filters or tests that want to react to undefined variables. For example a custom default filter can look like this:
检查传递的对象是否为未定义。这只是对Undefined
执行实例检查,但看起来更好。这可以用于自定义过滤器或测试,以便对未定义的变量做出反应。例如,自定义默认过滤器可以如下所示:def default(var, default=''): if is_undefined(var): return default return var
Exceptions¶ 异常 ¶
-
exception jinja2.TemplateError(message=None)¶
异常 jinja2.TemplateError(message=None) ¶ Baseclass for all template errors.
所有模板错误的基类。- Parameters: 参数:
message (str | None) –
message (str | None) -- Return type: 返回类型:
None 无
-
exception jinja2.UndefinedError(message=None)¶
异常 jinja2.UndefinedError(message=None) ¶ Raised if a template tries to operate on
Undefined
.
如果模板尝试对Undefined
进行操作,则引发异常。- Parameters: 参数:
message (str | None) –
消息(str | 无)-- Return type: 返回类型:
None 无
-
exception jinja2.TemplateNotFound(name, message=None)¶
异常 jinja2.TemplateNotFound(name, message=None) ¶ Raised if a template does not exist.
如果模板不存在,则引发此异常。Changelog 更新日志
Changed in version 2.11: If the given name is
Undefined
and no message was provided, anUndefinedError
is raised.
-
exception jinja2.TemplatesNotFound(names=(), message=None)¶
异常 jinja2.TemplatesNotFound(names=(), message=None) ¶ Like
TemplateNotFound
but raised if multiple templates are selected. This is a subclass ofTemplateNotFound
exception, so just catching the base exception will catch both.
类似于TemplateNotFound
,但在选择多个模板时引发。这是TemplateNotFound
异常的子类,因此只捕获基本异常即可同时捕获两者。Changelog 更新日志
Changed in version 2.11: If a name in the list of names is
Undefined
, a message about it being undefined is shown rather than the empty string.New in version 2.2.
-
exception jinja2.TemplateSyntaxError(message, lineno, name=None, filename=None)¶
异常 jinja2.TemplateSyntaxError(message, lineno, name=None, filename=None) ¶ Raised to tell the user that there is a problem with the template.
用于告知用户模板存在问题的异常。- Parameters: 参数:
- Return type: 返回类型:
None 无
- message¶ 消息 ¶
The error message. 错误消息。
- lineno¶ 行号 ¶
The line number where the error occurred.
发生错误的行号。
- name¶ 名称 ¶
The load name for the template.
模板的负载名称。
- filename¶ 文件名 ¶
The filename that loaded the template in the encoding of the file system (most likely utf-8, or mbcs on Windows systems).
加载模板的文件名,使用文件系统的编码(很可能是 utf-8,或者在 Windows 系统上是 mbcs)。
-
exception jinja2.TemplateRuntimeError(message=None)¶
异常 jinja2.TemplateRuntimeError(message=None) ¶ A generic runtime error in the template engine. Under some situations Jinja may raise this exception.
模板引擎中的通用运行时错误。在某些情况下,Jinja 可能会引发此异常。- Parameters: 参数:
message (str | None) –
message(str | None)-- Return type: 返回类型:
None 无
- 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.
类似于模板语法错误,但涵盖了模板中的某些内容在编译时引起错误,这不一定是由语法错误引起的。但它是TemplateSyntaxError
的直接子类,并具有相同的属性。
Custom Filters¶ 自定义过滤器¶
Filters are Python functions that take the value to the left of the
filter as the first argument and produce a new value. Arguments passed
to the filter are passed after the value.
过滤器是 Python 函数,它以过滤器左侧的值作为第一个参数,并生成一个新值。传递给过滤器的参数在值之后传递。
For example, the filter {{ 42|myfilter(23) }}
is called behind the
scenes as myfilter(42, 23)
.
例如,过滤器 {{ 42|myfilter(23) }}
在幕后被称为 myfilter(42, 23)
。
Jinja comes with some built-in filters. To use
a custom filter, write a function that takes at least a value
argument, then register it in Environment.filters
.
Jinja 带有一些内置过滤器。要使用自定义过滤器,请编写一个至少带有一个 value
参数的函数,然后在 Environment.filters
中注册它。
Here’s a filter that formats datetime objects:
这是一个格式化日期时间对象的过滤器:
def datetime_format(value, format="%H:%M %d-%m-%y"):
return value.strftime(format)
environment.filters["datetime_format"] = datetime_format
Now it can be used in templates:
现在它可以在模板中使用:
{{ article.pub_date|datetimeformat }}
{{ article.pub_date|datetimeformat("%B %Y") }}
Some decorators are available to tell Jinja to pass extra information to
the filter. The object is passed as the first argument, making the value
being filtered the second argument.
一些装饰器可用于告诉 Jinja 向过滤器传递额外的信息。对象作为第一个参数传递,使得被过滤的值成为第二个参数。
pass_environment()
passes theEnvironment
.
pass_environment()
通过了Environment
。pass_eval_context()
passes the Evaluation Context.
pass_eval_context()
通过评估上下文。pass_context()
passes the currentContext
.
pass_context()
通过当前的Context
。
Here’s a filter that converts line breaks into HTML <br>
and <p>
tags. It uses the eval context to check if autoescape is currently
enabled before escaping the input and marking the output safe.
这是一个将换行符转换为 HTML <br>
和 <p>
标记的过滤器。它使用 eval 上下文来检查当前是否启用了自动转义,然后转义输入并标记输出为安全。
import re
from jinja2 import pass_eval_context
from markupsafe import Markup, escape
@pass_eval_context
def nl2br(eval_ctx, value):
br = "<br>\n"
if eval_ctx.autoescape:
value = escape(value)
br = Markup(br)
result = "\n\n".join(
f"<p>{br.join(p.splitlines())}<\p>"
for p in re.split(r"(?:\r\n|\r(?!\n)|\n){2,}", value)
)
return Markup(result) if autoescape else result
Custom Tests¶ 自定义测试 ¶
Test are Python functions that take the value to the left of the test as
the first argument, and return True
or False
. Arguments passed
to the test are passed after the value.
测试是接受左侧数值作为第一个参数的 Python 函数,并返回 True
或 False
。传递给测试的参数在数值之后传递。
For example, the test {{ 42 is even }}
is called behind the scenes
as is_even(42)
.
例如,测试 {{ 42 is even }}
在幕后被称为 is_even(42)
。
Jinja comes with some built-in tests. To use a
custom tests, write a function that takes at least a value
argument,
then register it in Environment.tests
.
Jinja 带有一些内置测试。要使用自定义测试,编写一个至少接受 value
参数的函数,然后在 Environment.tests
中注册它。
Here’s a test that checks if a value is a prime number:
这是一个检查值是否为质数的测试:
import math
def is_prime(n):
if n == 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i == 0:
return False
return True
environment.tests["prime"] = is_prime
Now it can be used in templates:
现在它可以在模板中使用:
{% if value is prime %}
{{ value }} is a prime number
{% else %}
{{ value }} is not a prime number
{% endif %}
Some decorators are available to tell Jinja to pass extra information to
the test. The object is passed as the first argument, making the value
being tested the second argument.
一些装饰器可用于告诉 Jinja 将额外信息传递给测试。对象作为第一个参数传递,使得被测试的值成为第二个参数。
pass_environment()
passes theEnvironment
.
pass_environment()
通过Environment
。pass_eval_context()
passes the Evaluation Context.
pass_eval_context()
通过评估上下文。pass_context()
passes the currentContext
.
pass_context()
通过当前Context
。
Evaluation Context¶ 评估上下文 ¶
The evaluation context (short eval context or eval ctx) makes it
possible to activate and deactivate compiled features at runtime.
评估上下文(简称 eval 上下文或 eval ctx)使得在运行时可以激活和停用编译特性。
Currently it is only used to enable and disable automatic escaping, but
it can be used by extensions as well.
目前它仅用于启用和禁用自动转义,但也可以被扩展使用。
The autoescape
setting should be checked on the evaluation context,
not the environment. The evaluation context will have the computed value
for the current template.
autoescape
设置应该在评估上下文中进行检查,而不是在环境中。评估上下文将具有当前模板的计算值。
Instead of pass_environment
: 而不是 pass_environment
:
@pass_environment
def filter(env, value):
result = do_something(value)
if env.autoescape:
result = Markup(result)
return result
Use pass_eval_context
if you only need the setting:
如果您只需要该设置,请使用 pass_eval_context
@pass_eval_context
def filter(eval_ctx, value):
result = do_something(value)
if eval_ctx.autoescape:
result = Markup(result)
return result
Or use pass_context
if you need other context behavior as well:
或者如果您还需要其他上下文行为,请使用 pass_context
@pass_context
def filter(context, value):
result = do_something(value)
if context.eval_ctx.autoescape:
result = Markup(result)
return result
The evaluation context must not be modified at runtime. Modifications
must only happen with a nodes.EvalContextModifier
and
nodes.ScopedEvalContextModifier
from an extension, not on the
eval context object itself.
评估上下文在运行时不能被修改。修改只能通过扩展的 nodes.EvalContextModifier
和 nodes.ScopedEvalContextModifier
进行,不能直接在评估上下文对象本身上进行。
-
class jinja2.nodes.EvalContext(environment, template_name=None)¶
类 jinja2.nodes.EvalContext(environment, template_name=None) ¶ Holds evaluation time information. Custom attributes can be attached to it in extensions.
保存评估时间信息。可以在扩展中附加自定义属性。- Parameters: 参数:
environment (Environment) –
template_name (str | None) –
template_name(str | 无)-
- autoescape¶
True
orFalse
depending on if autoescaping is active or not.
True
或False
取决于自动转义是否激活。
- volatile¶ 易变的 ¶
True
if the compiler cannot evaluate some expressions at compile time. At runtime this should always beFalse
.
如果编译器无法在编译时评估某些表达式,则为True
。在运行时,这应始终为False
。
The Global Namespace¶ 全局命名空间 ¶
The global namespace stores variables and functions that should be
available without needing to pass them to Template.render()
. They
are also available to templates that are imported or included without
context. Most applications should only use Environment.globals
.
全局命名空间存储变量和函数,无需传递给 Template.render()
即可使用。它们也可用于没有上下文的导入或包含的模板。大多数应用程序只应使用 Environment.globals
。
Environment.globals
are intended for data that is common to all
templates loaded by that environment. Template.globals
are
intended for data that is common to all renders of that template, and
default to Environment.globals
unless they’re given in
Environment.get_template()
, etc. Data that is specific to a
render should be passed as context to Template.render()
.
Environment.globals
用于所有由该环境加载的模板的共同数据。 Template.globals
用于该模板的所有渲染的共同数据,并默认为 Environment.globals
,除非在 Environment.get_template()
中给出等等。特定于渲染的数据应作为上下文传递给 Template.render()
。
Only one set of globals is used during any specific rendering. If
templates A and B both have template globals, and B extends A, then
only B’s globals are used for both when using b.render()
.
在任何特定的渲染过程中,只使用一组全局变量。如果模板 A 和 B 都有模板全局变量,并且 B 继承 A,则在使用 b.render()
时只使用 B 的全局变量。
Environment globals should not be changed after loading any templates,
and template globals should not be changed at any time after loading the
template. Changing globals after loading a template will result in
unexpected behavior as they may be shared between the environment and
other templates.
在加载任何模板后,不应更改环境全局变量,并且在加载模板后任何时候都不应更改模板全局变量。在加载模板后更改全局变量将导致意外行为,因为它们可能在环境和其他模板之间共享。
Low Level API¶ 低级别 API ¶
The low level API exposes functionality that can be useful to understand some
implementation details, debugging purposes or advanced extension techniques. Unless you know exactly what you are doing we
don’t recommend using any of those.
低级 API 公开了一些功能,可以用于理解一些实现细节、调试目的或高级扩展技术。除非您确切知道自己在做什么,我们不建议使用其中任何一个。
- Environment.lex(source, name=None, filename=None)¶
Lex the given sourcecode and return a generator that yields tokens as tuples in the form
(lineno, token_type, value)
. This can be useful for extension development and debugging templates.
对给定的源代码进行词法分析,并返回一个以元组形式生成令牌的生成器(lineno, token_type, value)
。这对于扩展开发和调试模板非常有用。This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the
preprocess()
method.
这不执行预处理。如果您希望应用扩展的预处理,您必须通过preprocess()
方法过滤源。
- Environment.parse(source, name=None, filename=None)¶
Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates.
解析源代码并返回抽象语法树。编译器使用这个节点树将模板转换为可执行的源码或字节码。这对于调试或从模板中提取信息非常有用。If you are developing Jinja extensions this gives you a good overview of the node tree generated.
如果您正在开发 Jinja 扩展,这将为您提供生成的节点树的良好概述。- Parameters: 参数:
- Return type: 返回类型:
- Environment.preprocess(source, name=None, filename=None)¶
Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but not for
lex()
because there you usually only want the actual source tokenized.
使用所有扩展对源进行预处理。这在所有解析和编译方法中自动调用,但不适用于lex()
,因为在那里,您通常只想要实际的源代码标记化。
- Template.new_context(vars=None, shared=False, locals=None)¶
Create a new
Context
for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set toTrue
the data is passed as is to the context without adding the globals.
为此模板创建一个新的Context
。提供的变量将传递给模板。默认情况下,全局变量将添加到上下文中。如果设置为True
,则数据将原样传递给上下文,而不添加全局变量。locals
can be a dict of local variables for internal usage.
locals
可以是内部使用的本地变量字典。
- Template.root_render_func(context)¶
This is the low level render function. It’s passed a
Context
that has to be created bynew_context()
of the same template or a compatible template. This render function is generated by the compiler from the template code and returns a generator that yields strings.
这是低级别的渲染函数。它接收一个由相同模板或兼容模板创建的new_context()
生成的Context
。这个渲染函数是编译器从模板代码生成的,并返回一个生成器,生成字符串。If an exception in the template code happens the template engine will not rewrite the exception but pass through the original one. As a matter of fact this function should only be called from within a
render()
/generate()
/stream()
call.
如果模板代码中发生异常,模板引擎不会重写异常,而是传递原始异常。事实上,这个函数只应该在render()
/generate()
/stream()
调用内部调用。
- Template.blocks¶
A dict of block render functions. Each of these functions works exactly like the
root_render_func()
with the same limitations.
一个块渲染函数的字典。每个函数与具有相同限制的root_render_func()
完全相同。
- Template.is_up_to_date¶
This attribute is
False
if there is a newer version of the template available, otherwiseTrue
.
如果模板有新版本可用,则此属性为False
,否则为True
。
Note 注意
The low-level API is fragile. Future Jinja versions will try not to
change it in a backwards incompatible way but modifications in the Jinja
core may shine through. For example if Jinja introduces a new AST node
in later versions that may be returned by parse()
.
低级 API 很脆弱。未来的 Jinja 版本将尽量不以不兼容的方式进行更改,但是 Jinja 核心的修改可能会显现出来。例如,如果 Jinja 在后续版本中引入了一个新的 AST 节点,可能会被 parse()
返回。
The Meta API¶ Meta API ¶
Changelog 更新日志
New in version 2.2.
The meta API returns some information about abstract syntax trees that
could help applications to implement more advanced template concepts. All
the functions of the meta API operate on an abstract syntax tree as
returned by the Environment.parse()
method.
元 API 返回一些关于抽象语法树的信息,这些信息可以帮助应用程序实现更高级的模板概念。元 API 的所有函数都是在抽象语法树上操作的,该抽象语法树由 Environment.parse()
方法返回。
- jinja2.meta.find_undeclared_variables(ast)¶
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it’s not known which variables will be used depending on the path the execution takes at runtime, all variables are returned.
返回 AST 中将在运行时从上下文中查找的所有变量集合。因为在编译时不知道根据运行时执行的路径将使用哪些变量,所以返回所有变量。>>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True
Implementation
Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a
TemplateAssertionError
during compilation and as a matter of fact this function can currently raise that exception as well.
- jinja2.meta.find_referenced_templates(ast)¶
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used,
None
will be yielded.>>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.html', None]
This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed.