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(

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.
使用模板加载器而不是将字符串传递给 TemplateEnvironment.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:


The string marking the beginning of a block. Defaults to '{%'.
标记块开始的字符串。默认为 '{%'


The string marking the end of a block. Defaults to '%}'.
标记块结束的字符串。默认为 '%}'


The string marking the beginning of a print statement. Defaults to '{{'.
用于标记打印语句开头的字符串。默认为 '{{'


The string marking the end of a print statement. Defaults to '}}'.
用于标记打印语句结尾的字符串。默认为 '}}'


The string marking the beginning of a comment. Defaults to '{#'.
表示注释开始的字符串。默认为 '{#'


The string marking the end of a comment. Defaults to '#}'.
表示注释结束的字符串。默认为 '#}'


If given and a string, this will be used as prefix for line based statements. See also Line Statements.


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.


If this is set to True the first newline after a block is removed (block, not variable tag!). Defaults to False.
如果设置为 True ,则块后的第一个换行符将被移除(块,而不是变量标签!)。默认为 False


If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Defaults to False.
如果设置为 True ,则会从块的开头删除行的前导空格和制表符。默认为 False


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 应用程序来说是一个有用的默认值。


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.


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 扩展列表。这可以是字符串形式的导入路径或扩展类。有关更多信息,请查看扩展文档。


should the optimizer be enabled? Default is True.
优化器是否应启用?默认为 True


Undefined or a subclass of it that is used to represent undefined values in the template.
Undefined 或其子类,用于表示模板中未定义的值。


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 隐式转换为空字符串。


If set to True the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see Markup. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return True or False depending on autoescape should be enabled by default.
如果设置为 True ,则默认情况下启用 XML/HTML 自动转义功能。有关自动转义的更多详细信息,请参阅 Markup 。从 Jinja 2.4 开始,这也可以是一个可调用对象,它会传递模板名称并且必须返回 TrueFalse ,具体取决于是否应默认启用自动转义。

Changelog 更新日志

Changed in version 2.4: autoescape can now be a function


The template loader for this environment.


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 to 0 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.


Some loaders load templates from locations where the template sources may change (ie: file system or database). If auto_reload is set to True (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 (默认值),每次请求模板时,加载器都会检查源是否发生了变化,如果是,则重新加载模板。 为了提高性能,可以禁用该功能。


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.


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']) –

  • keep_trailing_newline (bool) –

  • extensions (Sequence[str | Type[Extension]]) –
    扩展 (Sequence[str | Type[Extension]]) -

  • optimized (bool) –  优化 (bool) -

  • undefined (Type[Undefined]) –
    未定义 (Type[Undefined]) -

  • 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) – 启用异步

shared shared ¶ 共享

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 is True, else False.
如果使用 Template 构造函数创建了模板,则会自动创建一个环境。这些环境被创建为共享环境,这意味着多个模板可以具有相同的匿名环境。对于所有共享环境,此属性为 True ,否则为 False

sandboxed 沙盒化的 ¶

If the environment is sandboxed this attribute is True. For the sandbox mode have a look at the documentation for the SandboxedEnvironment.
如果环境是沙盒化的,则此属性为 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, and enable_async parameters to match __init__.
在版本 3.1.2 中更改:添加了 newline_sequencekeep_trailing_newlineenable_async 参数以匹配 __init__

Parameters: 参数:
  • block_start_string (str) –

  • block_end_string (str) –

  • variable_start_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) –

  • extensions (Sequence[str | Type[Extension]]) –
    扩展(序列[str | Type[Extension]])–

  • optimized (bool) –  优化(布尔值)-

  • undefined (Type[Undefined]) –
    未定义(Undefined 类型)-

  • 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: 返回类型:

Environment 环境

undefined([hint, obj, name, exc])

Creates a new Undefined object for name. This is useful for filters or functions that may return undefined objects for some operations. All parameters except of hint should be provided as keyword parameters for better readability. The hint is used as error message for the exception if provided, otherwise the error message will be generated from obj and name automatically. The exception provided as exc is raised if something with the generated undefined object is done that the undefined object does not allow. The default exception is UndefinedError. If a hint is provided the name may be omitted.
name 创建一个新的 Undefined 对象。这对于可能对某些操作返回未定义对象的过滤器或函数非常有用。除了 hint 之外的所有参数都应该作为关键字参数提供,以便提高可读性。如果提供了 hint ,则将其用作异常的错误消息,否则错误消息将从 objname 自动生成。如果对生成的未定义对象执行了不允许的操作,则会引发提供的异常 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 or obj is known (for example because an attribute was accessed) it should be passed to the undefined object, even if a custom hint is provided. This gives undefined objects the possibility to enhance the error message.
如果 nameobj 已知(例如因为访问了属性),即使提供了自定义 hint ,也应将其传递给未定义的对象。这样未定义的对象就有可能增强错误消息。


Adds an extension after the environment was created.

Changelog 更新日志

New in version 2.5.

Parameters: 参数:

extension (str | Type[Extension]) –

Return type: 返回类型:



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: 返回类型:


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)
>>> expr(foo=42)

Per default the return value is converted to None if the expression returns an undefined value. This can be changed by setting undefined_to_none to False.
默认情况下,如果表达式返回未定义的值,则返回值将转换为 None 。可以通过将 undefined_to_none 设置为 False 来更改此设置。

>>> env.compile_expression('var')() is None
>>> env.compile_expression('var', undefined_to_none=False)()
Changelog 更新日志

New in version 2.1.

Parameters: 参数:
  • source (str) –  源代码 (str) -

  • undefined_to_none (bool) –
    undefined_to_none (bool) -

Return type: 返回类型:


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. If zip is None, 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 中。如果 zipNone ,模板将被存储在一个目录中,而不是一个压缩文件中。默认情况下使用 deflate 压缩算法。要切换到存储算法,可以将 zip 设置为 'stored'

extensions and filter_func are passed to list_templates(). Each template returned will be compiled to the target folder or zipfile.
extensionsfilter_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 to False 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: 返回类型:


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 a filter_func can be provided which is a callable that is passed a template name and should return True 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.

Parameters: 参数:
Return type: 返回类型:

List[str] List [ str ]

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.

Parameters: 参数:
  • template (str) –  模板(str)-

  • parent (str) –  父级(str)-

Return type: 返回类型:


get_template(name, parent=None, globals=None)
get_template(name,parent=None,globals=None) ¶

Load a template by name with loader and return a Template. If the template does not exist a TemplateNotFound 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: 返回类型:

Template 模板

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 a Template 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 a TemplatesNotFound 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: 返回类型:

Template 模板

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 is Undefined, an UndefinedError is raised instead. If no templates were found and names contains Undefined, the message is more helpful.

Changed in version 2.4: If names contains a Template 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, or get_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: 返回类型:

Template 模板

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: 返回类型:

Template 模板

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 ephemeral Environment instance behind the scenes.
也可以直接创建模板对象。这通常不被推荐。构造函数接受与 Environment 相同的大部分参数。使用相同环境参数创建的所有模板在幕后共享同一个临时 Environment 实例。

A template object should be considered immutable. Modifications on the object are not supported.

Parameters: 参数:
  • source (str | Template) –
    源(str | 模板)-

  • block_start_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) –

  • extensions (Sequence[str | Type[Extension]]) –
    extensions(字符串序列 | 扩展类型)-

  • optimized (bool) –  optimized(布尔值)-

  • undefined (Type[Undefined]) –

  • finalize (Callable[[...], Any] | None) –
    完成(可调用[[...], 任意] | 无)-

  • autoescape (bool | Callable[[str | None], bool]) –

  • 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 to Environment.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.


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


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.

Parameters: 参数:
  • args (Any) –  args(任意)-

  • kwargs (Any) –  kwargs(任意)-

Return type: 返回类型:


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() 相同的参数。

Parameters: 参数:
  • args (Any) –  args(任意)-

  • kwargs (Any) –  kwargs(任意)-

Return type: 返回类型:

Iterator[str] 迭代器[ str]

stream([context]) 流([上下文]) ¶

Works exactly like generate() but returns a TemplateStream.
功能与 generate() 完全相同,但返回 TemplateStream

Parameters: 参数:
  • args (Any) –  args(任意)-

  • kwargs (Any) –  kwargs(任意)-

Return type: 返回类型:

TemplateStream 模板流

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')
Parameters: 参数:
  • args (Any) –  args(任意)-

  • kwargs (Any) –  kwargs(任意)-

Return type: 返回类型:


async generate_async([context])
async generate_async([上下文])¶

An async version of generate(). Works very similarly but returns an async iterator instead.
generate() 的异步版本。工作方式非常相似,但返回一个异步迭代器。

Parameters: 参数:
  • args (Any) –  args (任意类型) -

  • kwargs (Any) –  kwargs(任意)-

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 the new_context() method.
当没有参数调用时,此方法的工作方式类似于 module 属性,但它会在每次调用时评估模板,而不是缓存它。还可以提供一个字典,然后将其用作上下文。参数与 new_context() 方法相同。

Parameters: 参数:
  • vars (Dict[str, Any] | None) –
    vars(Dict[str, Any] | None)-

  • shared (bool) –  shared(bool)-

  • locals (Mapping[str, Any] | None) –
    locals(Mapping[str, Any] | None)-

Return type: 返回类型:

TemplateModule 模板模块

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)
>>> t.module.foo() == u'42'

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 向客户端流式传输大型模板并在每次迭代后刷新时非常有用。

Parameters: 参数:

gen (Iterator[str]) –  gen(Iterator[str])-

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')
Parameters: 参数:
  • fp (str | IO[bytes]) –
    fp(字符串 | IO[字节])-

  • encoding (str | None) –
    编码(str | None)-

  • errors (str | None) –
    错误(str | None)-

Return type: 返回类型:


disable_buffering() 禁用缓冲() ¶

Disable the output buffering.

Return type: 返回类型:



Enable buffering. Buffer size items before yielding them.
启用缓冲。在生成之前缓冲 size 个项目。

Parameters: 参数:

size (int) –  大小(整数)-

Return type: 返回类型:


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'),

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(

The enabled_extensions is an iterable of all the extensions that autoescaping should be enabled for. Likewise disabled_extensions is a list of all templates it should be disabled for. If a template is loaded from a string then the default from default_for_string is used. If nothing matches then the initial value of autoescaping is set to the value of default.
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]) –

  • disabled_extensions (Collection[str]) –

  • default_for_string (bool) –

  • default (bool) –

Return type: 返回类型:

Callable[[str | None], bool]

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']),

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


The exception that the undefined object wants to raise. This is usually one of UndefinedError or SecurityError.
未定义的对象要引发的异常。通常为 UndefinedErrorSecurityError 之一。

_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 an UndefinedError.
一个可链式调用的未定义对象,其中 __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]) –

class jinja2.DebugUndefined
类 jinja2.DebugUndefined ¶

An undefined that returns the debug info when printed.

>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
>>> 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(
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: 返回类型:

Type[Undefined] 类型[未定义]

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

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 on vars are allowed from generated template code only. Template filters and global functions marked as pass_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 a resolve() method that doesn’t fail with a KeyError but returns an Undefined object for missing variables.
模板上下文支持只读字典操作( getkeysvaluesitemsiterkeysitervaluesiteritems__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 the Environment.globals or Template.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.globalsTemplate.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.


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


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() or pass_environment().
使用提供的参数和关键字参数调用可调用对象,但如果可调用对象具有 pass_context()pass_environment() ,则将活动上下文或环境注入为第一个参数。

Parameters: 参数:
  • _Context__obj (Callable[[...], Any]) –
    _Context__obj(Callable[[...], Any])-

  • args (Any) –  args(Any)-

  • kwargs (Any) –  kwargs(Any)-

Return type: 返回类型:

Any | Undefined 任何 | 未定义

get(key, default=None)

Look up a variable by name, or return a default if the key is not found.

Parameters: 参数:
  • key (str) – The variable name to look up.
    key (str) – 要查找的变量名称。

  • default (Any) – The value to return if the key is not found.
    default (Any) – 如果未找到键,则返回的值。

Return type: 返回类型:



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() ,而不是这个方法。各种查找函数使用该方法,而不是这个。

Parameters: 参数:

key (str) – The variable name to look up.

Return type: 返回类型:

Any | Undefined 任何| 未定义


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__() 使用此方法。不要直接调用此方法。

Parameters: 参数:

key (str) – The variable name to look up.
key (str) - 要查找的变量名称。

Return type: 返回类型:



Get a new dict with the exported variables.

Return type: 返回类型:

Dict[str, Any] Dict[str, Any]


Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.

Return type: 返回类型:

Dict[str, Any] Dict[str, Any]

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 a get_template method that calls the loader’s load method to get the Template 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 a TemplateNotFound 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 returns False the template will be reloaded.
元组中的最后一项是 uptodate 函数。如果启用了自动重新加载,则始终调用该函数以检查模板是否更改。不传递任何参数,因此函数必须在某个地方存储旧状态(例如在闭包中)。如果返回 False ,则重新加载模板。

Parameters: 参数:
Return type: 返回类型:

Tuple[str, str | None, Callable[[], bool] | None]
Tuple[str, str | None, Callable[[], bool] | None]

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.
加载模板。此方法在缓存中查找模板或通过调用 get_source() 来加载一个模板。子类不应覆盖此方法,因为对其他加载器集合(如 PrefixLoaderChoiceLoader )进行操作的加载器不会调用此方法,而是直接调用 get_source

Parameters: 参数:
Return type: 返回类型:

Template 模板

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 the project.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.

Parameters: 参数:

mapping (Mapping[str, str]) –
映射(Mapping[str, str])-

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) or None 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 return True if the template is still up to date. For more details have a look at BaseLoader.get_source() which has the same return value.
如果启用了自动重新加载,将调用 uptodatefunc 函数,并且必须返回 True 以表示模板是否仍然是最新的。有关更多详细信息,请参阅具有相同返回值的 BaseLoader.get_source()

Parameters: 参数:

load_func (Callable[[str], str | Tuple[str, str | None, Callable[[], bool] | None] | None]) –
load_func(Callable[[str], str | Tuple[str, str | None, Callable[[], bool] | None] | None])-

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]) –

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() and dump_bytecode(). Both of these methods are passed a Bucket.
要实现自己的字节码缓存,您必须继承此类并覆盖 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:

    def dump_bytecode(self, bucket):
        filename = path.join(self.directory, bucket.key)
        with open(filename, 'wb') as f:

A more advanced version of a filesystem based bytecode cache is part of Jinja.
文件系统基于字节码缓存的更高级版本是 Jinja 的一部分。


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: 返回类型:



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: 返回类型:



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: 返回类型:


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

  • key (str) –  键(str)-

  • checksum (str) –  校验和(str)-

environment 环境 ¶

The Environment that created the bucket.
创建存储桶的 Environment

key 键 ¶

The unique cache key for this bucket


The bytecode if it’s loaded, otherwise None.
如果加载了字节码,则为字节码,否则为 None


Resets the bucket (unloads the bytecode).

Return type: 返回类型:



Loads bytecode from a file or file like object.

Parameters: 参数:

f (BinaryIO) –  f(BinaryIO)-

Return type: 返回类型:



Dump the bytecode into the file or file like object passed.

Parameters: 参数:

f (IO[bytes]) –  f(IO[bytes])-

Return type: 返回类型:



Load bytecode from bytes.

Parameters: 参数:

string (bytes) –

Return type: 返回类型:


bytecode_to_string() bytecode_to_string()¶

Return the bytecode as bytes.

Return type: 返回类型:

bytes 字节

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 方法清除缓存。

Parameters: 参数:
  • directory (str | None) –
    目录 (str | None) –

  • pattern (str) –  模式 (str) –

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: 参数:
  • client (_MemcachedClient) –

  • prefix (str) –  前缀(str)-

  • timeout (int | None) –
    超时(int | 无)-

  • ignore_memcache_errors (bool) –
    ignore_memcache_errors (bool) -

class MinimalClientInterface
set(key, value[, timeout])

Stores the bytecode in the cache. value is a string and timeout 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 是键的超时时间。如果未提供超时时间,则应假定默认超时时间或无超时时间;如果提供了超时时间,则应为一个整数,表示缓存项应存在的秒数。


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 asyncawait 语法。对于模板设计师来说,这种支持(在启用时)是完全透明的,模板看起来仍然完全一样。但是,开发人员应该意识到它的实现方式,因为它会影响您可以使用的 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 uses async 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 invokes async_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'

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 to 0 to get the old behavior back. The default is 5.
配置 truncate 过滤器的默认容差。容差在 2.9 中引入,但为了恢复与旧模板的兼容性,可以将其配置为 0 以恢复旧行为。默认值为 5


A string that defines the items for the rel attribute of generated links with the urlize filter. These items are always added. The default is noopener.
一个字符串,定义了使用 urlize 过滤器生成链接的 rel 属性的项目。这些项目始终会被添加。默认值为 noopener


The default target that is issued for links from the urlize filter if no other target is defined by the call explicitly.
如果在调用中没有明确定义其他目标,则为来自 urlize 过滤器的链接发出的默认目标。


Recognize URLs that start with these schemes in addition to the default http://, https://, and mailto:.
除了默认的 http://https://mailto: 之外,识别以这些方案开头的 URL。


If this is set to a value other than None then the tojson 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 is indent. The default dump function is json.dumps.
如果将其设置为非 None 的值,则 tojson 过滤器将使用此函数而不是默认函数进行转储。请注意,此函数应接受可能从过滤器中传递的未来任意额外参数。目前可能传递的唯一参数是 indent 。默认转储函数为 json.dumps


Keyword arguments to be passed to the dump function. The default is {'sort_keys': True}.
传递给转储函数的关键字参数。默认值为 {'sort_keys': True}


If this is set to True, {% trans %} blocks of the i18n Extension will always unify linebreaks and surrounding whitespace as if the trimmed 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 环境添加自定义过滤器或函数,则这些辅助函数和类非常有用。


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, use pass_eval_context(). If only Context.environment is needed, use pass_environment().
如果只需要 Context.eval_context ,请使用 pass_eval_context() 。如果只需要 Context.environment ,请使用 pass_environment()

Changelog 更新日志

New in version 3.0.0: Replaces contextfunction and contextfilter.

Parameters: 参数:

f (F) –

Return type: 返回类型



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, use pass_environment().
如果只需要 EvalContext.environment ,请使用 pass_environment()

Changelog 更新日志

New in version 3.0.0: Replaces evalcontextfunction and evalcontextfilter.

Parameters: 参数:

f (F) –  f(F)-

Return type: 返回类型:



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 and environmentfilter.

Parameters: 参数:

f (F) –  f(F)-

Return type: 返回类型:



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: 返回类型:



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
Parameters: 参数:

obj (Any) –  obj(任意类型)-

Return type: 返回类型:

bool 布尔值

Exceptions 异常 ¶

exception jinja2.TemplateError(message=None)
异常 jinja2.TemplateError(message=None) ¶

Baseclass for all template errors.

Parameters: 参数:

message (str | None) –
message (str | None) -

Return type: 返回类型:


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: 返回类型:


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, an UndefinedError is raised.

Parameters: 参数:
  • name (str | Undefined | None) –
    名称(str | 未定义 | 无)-

  • message (str | None) –
    消息(str | 无)-

Return type: 返回类型:


exception jinja2.TemplatesNotFound(names=(), message=None)
异常 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.
类似于 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.

Parameters: 参数:
  • names (Sequence[str | Undefined]) –
    names(Sequence[str | Undefined])-

  • message (str | None) –
    消息 (str | None) –

Return type: 返回类型:


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: 参数:
  • message (str) –

  • lineno (int) –  行号 (整数) –

  • name (str | None) –
    名称 (字符串 | 无) –

  • filename (str | None) –
    文件名(字符串 | 无)-

Return type: 返回类型:


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: 返回类型:


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 的直接子类,并具有相同的属性。

Parameters: 参数:
  • message (str) –

  • lineno (int) –

  • name (str | None) –
    名称(字符串 | 无)–

  • filename (str | None) –
    文件名(字符串 | 无)–

Return type: 返回类型:


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 向过滤器传递额外的信息。对象作为第一个参数传递,使得被过滤的值成为第二个参数。

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

def nl2br(eval_ctx, value):
    br = "<br>\n"

    if eval_ctx.autoescape:
        value = escape(value)
        br = Markup(br)

    result = "\n\n".join(
        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 函数,并返回 TrueFalse 。传递给测试的参数在数值之后传递。

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 将额外信息传递给测试。对象作为第一个参数传递,使得被测试的值成为第二个参数。

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

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

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

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.EvalContextModifiernodes.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 | 无)-


True or False depending on if autoescaping is active or not.
TrueFalse 取决于自动转义是否激活。

volatile 易变的 ¶

True if the compiler cannot evaluate some expressions at compile time. At runtime this should always be False.
如果编译器无法在编译时评估某些表达式,则为 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() 方法过滤源。

Parameters: 参数:
  • source (str) –  源代码 (str) -

  • name (str | None) –
    名称 (str | None) -

  • filename (str | None) –
    文件名 (str | None) -

Return type: 返回类型:

Iterator[Tuple[int, str, str]]
迭代器[元组[ int, str, str]]

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: 参数:
  • source (str) –  源(str)-

  • name (str | None) –
    名称(str | None)-

  • filename (str | None) –
    文件名 (str | None) -

Return type: 返回类型:

Template 模板

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() ,因为在那里,您通常只想要实际的源代码标记化。

Parameters: 参数:
  • source (str) –  源代码 (str) -

  • name (str | None) –
    名称 (str | None) -

  • filename (str | None) –
    文件名(str | 无)-

Return type: 返回类型:


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 to True 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 可以是内部使用的本地变量字典。

Parameters: 参数:
  • vars (Dict[str, Any] | None) –
    vars(Dict[str, Any] | None)-

  • shared (bool) –  shared(bool)-

  • locals (Mapping[str, Any] | None) –
    locals(Mapping[str, Any] | None)-

Return type: 返回类型:

Context 上下文


This is the low level render function. It’s passed a Context that has to be created by new_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() 调用内部调用。


A dict of block render functions. Each of these functions works exactly like the root_render_func() with the same limitations.
一个块渲染函数的字典。每个函数与具有相同限制的 root_render_func() 完全相同。


This attribute is False if there is a newer version of the template available, otherwise True.
如果模板有新版本可用,则此属性为 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() 方法返回。


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'}


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.


ast (Template) –

Return type:



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.


ast (Template) –

Return type:

Iterator[str | None]