高层 API

最后更新于:2022-04-01 04:03:02

高层 API 即是你会在应用中用于加载并渲染模板的 API 。 [*低层 API*](http://docs.jinkan.org/docs/jinja2/api.html#low-level-api) 相反,只在你想深入挖掘 Jinja2 或 [*开发扩展*](http://docs.jinkan.org/docs/jinja2/extensions.html#jinja-extensions) 时有用。 *class *jinja2.Environment([*options*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment "Permalink to this definition") 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. Here the possible initialization parameters: > > > block_start_string > > The string marking the begin 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 begin 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 begin 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 [*行语句*](http://docs.jinkan.org/docs/jinja2/templates.html#line-statements). > > line_comment_prefix > > > > If given and a string, this will be used as prefix for line based based comments. See also [*行语句*](http://docs.jinkan.org/docs/jinja2/templates.html#line-statements). > > > > 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 to 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 to 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. > > 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. > > > > 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*](http://docs.jinkan.org/docs/jinja2/extensions.html#jinja-extensions). > > optimized > > should the optimizer be enabled? Default is True. > > undefined > > [Undefined](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Undefined "jinja2.Undefined") or a subclass of it that is used to represent undefined values in the template. > > 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. > > autoescape > > > > If set to true the XML/HTML autoescaping feature is enabled by default. For more details about auto escaping 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 Falsedepending on autoescape should be enabled by default. > > > > Changed in version 2.4: autoescape can now be a function > > > > > > loader > > The template loader for this environment. > > cache_size > > The size of the cache. Per default this is 50 which means that if more than 50 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. > > auto_reload > > 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. > > 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. > > See [*字节码缓存*](http://docs.jinkan.org/docs/jinja2/api.html#bytecode-cache) for more information. > > > > shared[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.shared "Permalink to this definition") 如果模板通过 [Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template") 构造函数创建,会自动创建一个环境。这 些环境被创建为共享的环境,这意味着多个模板拥有相同的匿名环境。对所有 模板共享环境,这个属性为 True ,反之为 False 。 sandboxed[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.sandboxed "Permalink to this definition") 如果环境在沙箱中,这个属性为 True 。沙箱模式见文档中的[SandboxedEnvironment](http://docs.jinkan.org/docs/jinja2/sandbox.html#jinja2.sandbox.SandboxedEnvironment "jinja2.sandbox.SandboxedEnvironment") 。 filters[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.filters "Permalink to this definition") 该环境的过滤器字典。只要没有加载过模板,添加新过滤器或删除旧的都是 安全的。自定义过滤器见 [*自定义过滤器*](http://docs.jinkan.org/docs/jinja2/api.html#writing-filters) 。有效的过滤器名称见 [*标识符的说明*](http://docs.jinkan.org/docs/jinja2/api.html#identifier-naming) 。 tests[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.tests "Permalink to this definition") 该环境的测试函数字典。只要没有加载过模板,修改这个字典都是安全的。 自定义测试见 see [*自定义测试*](http://docs.jinkan.org/docs/jinja2/api.html#writing-tests) 。有效的测试名见 [*标识符的说明*](http://docs.jinkan.org/docs/jinja2/api.html#identifier-naming) 。 globals[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.globals "Permalink to this definition") 一个全局变量字典。这些变量在模板中总是可用。只要没有加载过模板,修 改这个字典都是安全的。更多细节见 [*全局命名空间*](http://docs.jinkan.org/docs/jinja2/api.html#global-namespace) 。有效的 对象名见 [*标识符的说明*](http://docs.jinkan.org/docs/jinja2/api.html#identifier-naming)。 overlay([*options*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.overlay "Permalink to this definition") Create a new overlay environment that shares all the data with the current environment except of 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. undefined([*hint*, *obj*, *name*, *exc*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.undefined "Permalink to this definition") 为 name 创建一个新 [Undefined](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Undefined "jinja2.Undefined") 对象。这对可能为某些操作返回 未定义对象过滤器和函数有用。除了 hint ,为了良好的可读性,所有参数 应该作为关键字参数传入。如果提供了 hint ,它被用作异常的错误消息, 否则错误信息会由 obj 和name 自动生成。 exc 为生成未定义对象而 不允许未定义的对象时抛出的异常。默认的异常是 [UndefinedError](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.UndefinedError "jinja2.UndefinedError") 。 如果提供了 hint , name 会被发送。 创建一个未定义对象的最常用方法是只提供名称: ~~~ return environment.undefined(name='some_name') ~~~ 这意味着名称 some_name 未被定义。如果名称来自一个对象的属性,把 持有它的对象告知未定义对象对丰富错误消息很有意义: ~~~ if not hasattr(obj, 'attr'): return environment.undefined(obj=obj, name='attr') ~~~ 更复杂的例子中,你可以提供一个 hint 。例如 [first()](http://docs.jinkan.org/docs/jinja2/templates.html#first "first") 过滤器 用这种方法创建一个未定义对象: ~~~ return environment.undefined('no first item, sequence was empty') ~~~ 如果 name 或 obj 是已知的(比如访问了了一个属性),它应该传递给 未定义对象,即使提供了自定义的 hint 。这让未定义对象有可能增强错误 消息。 add_extension(*extension*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.add_extension "Permalink to this definition") Adds an extension after the environment was created. New in version 2.5. compile_expression(*source*, *undefined_to_none=True*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.compile_expression "Permalink to this definition") 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. 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 setting undefined_to_none to False. ~~~ >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined ~~~ New in version 2.1. compile_templates(*target*, *extensions=None*, *filter_func=None*, *zip='deflated'*,*log_function=None*, *ignore_errors=True*, *py_compile=False*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.compile_templates "Permalink to this definition") Finds all the templates the loader can find, compiles them and stores them intarget. If zip is None, instead of in a zipfile, the templates will be 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'. extensions and filter_func are passed to [list_templates()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.list_templates "jinja2.Environment.list_templates"). Each template returned will be compiled to the target folder or zipfile. 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. If py_compile is set to True .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don’t give much benefit. New in version 2.4. extend(***attributes*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.extend "Permalink to this definition") Add the items to the instance of the environment if they do not exist yet. This is used by [*extensions*](http://docs.jinkan.org/docs/jinja2/extensions.html#writing-extensions) to register callbacks and configuration values without breaking inheritance. from_string(*source*, *globals=None*, *template_class=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.from_string "Permalink to this definition") Load a template from a string. This parses the source given and returns a[Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template") object. get_or_select_template(*template_name_or_list*, *parent=None*, *globals=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.get_or_select_template "Permalink to this definition") Does a typecheck and dispatches to [select_template()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.select_template "jinja2.Environment.select_template") if an iterable of template names is given, otherwise to [get_template()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.get_template "jinja2.Environment.get_template"). New in version 2.3. get_template(*name*, *parent=None*, *globals=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.get_template "Permalink to this definition") Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a [Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template"). If the parent parameter is notNone, [join_path()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.join_path "jinja2.Environment.join_path") is called to get the real template name before loading. The globals parameter can be used to provide template wide globals. These variables are available in the context at render time. If the template does not exist a [TemplateNotFound](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.TemplateNotFound "jinja2.TemplateNotFound") exception is raised. Changed in version 2.4: If name is a [Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template") object it is returned from the function unchanged. join_path(*template*, *parent*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.join_path "Permalink to this definition") 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. Subclasses may override this method and implement template path joining here. list_templates(*extensions=None*, *filter_func=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.list_templates "Permalink to this definition") Returns a list of templates for this environment. This requires that the loader supports the loader’s list_templates() method. 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. If the loader does not support that, a TypeError is raised. New in version 2.4. select_template(*names*, *parent=None*, *globals=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.select_template "Permalink to this definition") Works like [get_template()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.get_template "jinja2.Environment.get_template") but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a [TemplatesNotFound](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.TemplatesNotFound "jinja2.TemplatesNotFound") exception. New in version 2.3. Changed in version 2.4: If names contains a [Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template") object it is returned from the function unchanged. *class *jinja2.Template[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "Permalink to this definition") The central template object. This class represents a compiled template and is used to evaluate it. Normally the template object is generated from an [Environment](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment "jinja2.Environment") but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it’s not possible to specify a loader. Every template object has a few methods and members that are guaranteed to exist. However it’s important that a template object should be considered immutable. Modifications on the object are not supported. Template objects created from the constructor rather than an environment do have an environment attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings. ~~~ >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') u'Hello John Doe!' ~~~ ~~~ >>> stream = template.stream(name='John Doe') >>> stream.next() u'Hello John Doe!' >>> stream.next() Traceback (most recent call last): ... StopIteration ~~~ globals[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.globals "Permalink to this definition") 该模板的全局变量字典。修改这个字典是不安全的,因为它可能与其它模板或 加载这个模板的环境共享。 name[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.name "Permalink to this definition") 模板的加载名。如果模板从字符串加载,这个值为 None 。 filename[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.filename "Permalink to this definition") 模板在文件系统上的文件名,如果没有从文件系统加载,这个值为 None 。 render([*context*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.render "Permalink to this definition") 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: ~~~ template.render(knights='that say nih') template.render({'knights': 'that say nih'}) ~~~ This will return the rendered template as unicode string. generate([*context*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.generate "Permalink to this definition") 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 unicode strings. It accepts the same arguments as [render()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.render "jinja2.Template.render"). stream([*context*])[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.stream "Permalink to this definition") Works exactly like [generate()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.generate "jinja2.Template.generate") but returns a TemplateStream. make_module(*vars=None*, *shared=False*, *locals=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.make_module "Permalink to this definition") This method works like the [module](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.module "jinja2.Template.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()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.new_context "jinja2.Template.new_context") method. module[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template.module "Permalink to this definition") 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: ~~~ >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> unicode(t.module) u'23' >>> t.module.foo() u'42' ~~~ *class *jinja2.environment.TemplateStream[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.environment.TemplateStream "Permalink to this definition") 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 unicode string is yielded. If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration. disable_buffering()[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.environment.TemplateStream.disable_buffering "Permalink to this definition") Disable the output buffering. dump(*fp*, *encoding=None*, *errors='strict'*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.environment.TemplateStream.dump "Permalink to this definition") Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specify an encoding. Example usage: ~~~ Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') ~~~ enable_buffering(*size=5*)[¶](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.environment.TemplateStream.enable_buffering "Permalink to this definition") Enable buffering. Buffer size items before yielding them.
';