高层 API
高层 API 即是你会在应用中用于加载并渲染模板的 API 。 低层 API相反,只在你想深入挖掘 Jinja2 或 开发扩展 时有用。
- class _jinja2.Environment([_options])
- The core component of Jinja is the Environment. It containsimportant shared variables like configuration, filters, tests,globals and others. Instances of this class may be modified ifthey are not shared and if no template was loaded so far.Modifications on environments after the first template was loadedwill 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 basedstatements. See also 行语句.
- line_comment_prefix
If given and a string, this will be used as prefix for line basedbased comments. See also 行语句.
New in version 2.2.
- trim_blocks
- If this is set to True the first newline after a block isremoved (block, not variable tag!). Defaults to False.
- lstrip_blocks
- If this is set to True leading spaces and tabs are strippedfrom 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 auseful default for Linux and OS X systems as well as webapplications.
- 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 pathsas strings or extension classes. For more information have alook at the extensions documentation.
- optimized
- should the optimizer be enabled? Default is True.
- undefined
- Undefined or a subclass of it that is used to representundefined values in the template.
- finalize
- A callable that can be used to process the result of a variableexpression before it is output. For example one can convertNone implicitly into an empty string here.
- autoescape
If set to true the XML/HTML autoescaping feature is enabled bydefault. For more details about auto escaping seeMarkup. As of Jinja 2.4 this can alsobe a callable that is passed the template name and has toreturn True or False depending on autoescape should beenabled 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 meansthat if more than 50 templates are loaded the loader will cleanout the least recently used template. If the cache size is set to0 templates are recompiled all the time, if the cache size is-1 the cache will not be cleaned.
- auto_reload
- Some loaders load templates from locations where the templatesources may change (ie: file system or database). Ifauto_reload is set to True (default) every time a template isrequested the loader checks if the source changed and if yes, itwill reload the template. For higher performance it’s possible todisable that.
- bytecode_cache
If set to a bytecode cache object, this object will provide acache for the internal Jinja bytecode so that templates don’thave to be parsed if they were not changed.
See 字节码缓存 for more information.
- shared
如果模板通过 Template 构造函数创建,会自动创建一个环境。这些环境被创建为共享的环境,这意味着多个模板拥有相同的匿名环境。对所有模板共享环境,这个属性为 True ,反之为 False 。
如果环境在沙箱中,这个属性为 True 。沙箱模式见文档中的SandboxedEnvironment 。
该环境的过滤器字典。只要没有加载过模板,添加新过滤器或删除旧的都是安全的。自定义过滤器见 自定义过滤器 。有效的过滤器名称见标识符的说明 。
该环境的测试函数字典。只要没有加载过模板,修改这个字典都是安全的。自定义测试见 see 自定义测试 。有效的测试名见标识符的说明 。
一个全局变量字典。这些变量在模板中总是可用。只要没有加载过模板,修改这个字典都是安全的。更多细节见 全局命名空间 。有效的对象名见 标识符的说明 。
- Create a new overlay environment that shares all the data with thecurrent environment except of cache and the overridden attributes.Extensions cannot be removed for an overlayed environment. An overlayedenvironment automatically gets all the extensions of the environment itis linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was setup completely. Not all attributes are truly linked, some are justcopied over so modifications on the original environment may not shinethrough.
- undefined([hint, obj, name, exc])
- 为 name 创建一个新 Undefined 对象。这对可能为某些操作返回未定义对象过滤器和函数有用。除了 hint ,为了良好的可读性,所有参数应该作为关键字参数传入。如果提供了 hint ,它被用作异常的错误消息,否则错误信息会由 obj 和 name 自动生成。 exc 为生成未定义对象而不允许未定义的对象时抛出的异常。默认的异常是 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() 过滤器用这种方法创建一个未定义对象:
return environment.undefined('no first item, sequence was empty')
如果 name 或 obj 是已知的(比如访问了了一个属性),它应该传递给未定义对象,即使提供了自定义的 hint 。这让未定义对象有可能增强错误消息。
New in version 2.5.
- compileexpression(_source, undefined_to_none=True)
- A handy helper method that returns a callable that accepts keywordarguments that appear as variables in the expression. If called itreturns the result of the expression.
This is useful if applications want to use the same rules as Jinjain 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 theexpression returns an undefined value. This can be changedby 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.
- compiletemplates(_target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False)
- Finds all the templates the loader can find, compiles themand stores them in target. If zip is None, instead of in azipfile, the templates will be will be stored in a directory.By default a deflate zip algorithm is used, to switch tothe stored algorithm, zip can be set to 'stored'.
extensions and filter_func are passed to list_templates().Each template returned will be compiled to the target folder orzipfile.
By default template compilation errors are ignored. In case alog function is provided, errors are logged. If you want templatesyntax 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 thetarget instead of standard .py files. This flag does not do anythingon pypy and Python 3 where pyc files are not picked up by itself anddon’t give much benefit.
New in version 2.4.
- extend(**attributes)
Add the items to the instance of the environment if they do not existyet. This is used by extensions to registercallbacks and configuration values without breaking inheritance.
Load a template from a string. This parses the source given andreturns a Template object.
getor_select_template(_template_name_or_list, parent=None, globals=None)
- Does a typecheck and dispatches to select_template()if an iterable of template names is given, otherwise toget_template().
New in version 2.3.
- gettemplate(_name, parent=None, globals=None)
- Load a template from the loader. If a loader is configured thismethod ask the loader for the template and returns a Template.If the parent parameter is not None, join_path() is calledto 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 exception israised.
Changed in version 2.4: If name is a Template object it is returned from thefunction unchanged.
- joinpath(_template, parent)
- Join a template with the parent. By default all the lookups arerelative to the loader root so this method returns the _template_parameter unchanged, but if the paths should be relative to theparent template, this function can be used to calculate the realtemplate name.
Subclasses may override this method and implement template pathjoining here.
- listtemplates(_extensions=None, filter_func=None)
- Returns a list of templates for this environment. This requiresthat the loader supports the loader’slist_templates() method.
If there are other files in the template folder besides theactual templates, the returned list can be filtered. There are twoways: either extensions is set to a list of file extensions fortemplates, or a filter_func can be provided which is a callable thatis passed a template name and should return True if it should end upin the result list.
If the loader does not support that, a TypeError is raised.
New in version 2.4.
- selecttemplate(_names, parent=None, globals=None)
- Works like get_template() but tries a number of templatesbefore it fails. If it cannot find any of the templates, it willraise a TemplatesNotFound exception.
New in version 2.3.
Changed in version 2.4: If names contains a Template object it is returnedfrom the function unchanged.
- _class _jinja2.Template
- The central template object. This class represents a compiled templateand is used to evaluate it.
Normally the template object is generated from an Environment butit also has a constructor that makes it possible to create a templateinstance directly using the constructor. It takes the same arguments asthe environment constructor but it’s not possible to specify a loader.
Every template object has a few methods and members that are guaranteedto exist. However it’s important that a template object should beconsidered immutable. Modifications on the object are not supported.
Template objects created from the constructor rather than an environmentdo have an environment attribute that points to a temporary environmentthat is probably shared with other templates created with the constructorand 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
该模板的全局变量字典。修改这个字典是不安全的,因为它可能与其它模板或加载这个模板的环境共享。
模板的加载名。如果模板从字符串加载,这个值为 None 。
模板在文件系统上的文件名,如果没有从文件系统加载,这个值为 None 。
- This method accepts the same arguments as the dict constructor:A dict, a dict subclass or some keyword arguments. If no argumentsare 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])
- For very large templates it can be useful to not render the wholetemplate at once but evaluate each statement after another and yieldpiece for piece. This method basically does exactly that and returnsa generator that yields one item after another as unicode strings.
It accepts the same arguments as render().
- stream([context])
Works exactly like generate() but returns aTemplateStream.
This method works like the module attribute when calledwithout arguments but it will evaluate the template on every callrather than caching it. It’s also possible to providea dict which is then used as context. The arguments are the sameas for the new_context() method.
- The template as module. This is used for imports in thetemplate runtime but is also useful if one wants to accessexported 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
- A template stream works pretty much like an ordinary python generatorbut it can buffer multiple items to reduce the number of total iterations.Per default the output is unbuffered which means that for every unbufferedinstruction in the template one unicode string is yielded.
If buffering is enabled with a buffer size of 5, five items are combinedinto a new unicode string. This is mainly useful if you are streamingbig templates to a client via WSGI which flushes after each iteration.
- disable_buffering()
Disable the output buffering.
- Dump the complete stream into a file or file-like object.Per default unicode strings are written, if you want to encodebefore writing specify an encoding.
Example usage:
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')