高层 API

2018-02-24 15:39 更新

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

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.

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 行语句.

line_comment_prefix

If given and a string, this will be used as prefix for line based based comments. See also 行语句.

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.

optimized

should the optimizer be enabled? Default is True.

undefined

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 字节码缓存 for more information.

shared

如果模板通过 Template 构造函数创建,会自动创建一个环境。这 些环境被创建为共享的环境,这意味着多个模板拥有相同的匿名环境。对所有 模板共享环境,这个属性为 True ,反之为 False 。

sandboxed

如果环境在沙箱中,这个属性为 True 。沙箱模式见文档中的SandboxedEnvironment 。

filters

该环境的过滤器字典。只要没有加载过模板,添加新过滤器或删除旧的都是 安全的。自定义过滤器见 自定义过滤器 。有效的过滤器名称见 标识符的说明 。

tests

该环境的测试函数字典。只要没有加载过模板,修改这个字典都是安全的。 自定义测试见 see 自定义测试 。有效的测试名见 标识符的说明 。

globals

一个全局变量字典。这些变量在模板中总是可用。只要没有加载过模板,修 改这个字典都是安全的。更多细节见 全局命名空间 。有效的 对象名见 标识符的说明

overlay([options])

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([hintobjnameexc])

为 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 。这让未定义对象有可能增强错误 消息。

add_extension(extension)

Adds an extension after the environment was created.

New in version 2.5.

compile_expression(sourceundefined_to_none=True)

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(targetextensions=Nonefilter_func=Nonezip='deflated',log_function=Noneignore_errors=Truepy_compile=False)

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

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.

from_string(sourceglobals=Nonetemplate_class=None)

Load a template from a string. This parses the source given and returns aTemplate object.

get_or_select_template(template_name_or_listparent=Noneglobals=None)

Does a typecheck and dispatches to select_template() if an iterable of template names is given, otherwise to get_template().

New in version 2.3.

get_template(nameparent=Noneglobals=None)

Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a Template. If the parent parameter is notNone, 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 exception is raised.

Changed in version 2.4: If name is a Template object it is returned from the function unchanged.

join_path(templateparent)

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=Nonefilter_func=None)

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(namesparent=Noneglobals=None)

Works like get_template() but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a TemplatesNotFound exception.

New in version 2.3.

Changed in version 2.4: If names contains a Template object it is returned from the function unchanged.

class jinja2.Template

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

该模板的全局变量字典。修改这个字典是不安全的,因为它可能与其它模板或 加载这个模板的环境共享。

name

模板的加载名。如果模板从字符串加载,这个值为 None 。

filename

模板在文件系统上的文件名,如果没有从文件系统加载,这个值为 None 。

render([context])

This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:

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

stream([context])

Works exactly like generate() but returns a TemplateStream.

make_module(vars=Noneshared=Falselocals=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

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

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

Disable the output buffering.

dump(fpencoding=Noneerrors='strict')

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)

Enable buffering. Buffer size items before yielding them.

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号