高層 API 即是你會(huì)在應(yīng)用中用于加載并渲染模板的 API 。?低層 API?相反,只在你想深入挖掘 Jinja2 或?開(kāi)發(fā)擴(kuò)展?時(shí)有用。
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?行語(yǔ)句.
line_comment_prefix
If given and a string, this will be used as prefix for line based based comments. See also?行語(yǔ)句.
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?字節(jié)碼緩存?for more information.
如果模板通過(guò)?Template?構(gòu)造函數(shù)創(chuàng)建,會(huì)自動(dòng)創(chuàng)建一個(gè)環(huán)境。這 些環(huán)境被創(chuàng)建為共享的環(huán)境,這意味著多個(gè)模板擁有相同的匿名環(huán)境。對(duì)所有 模板共享環(huán)境,這個(gè)屬性為?True?,反之為?False?。
如果環(huán)境在沙箱中,這個(gè)屬性為?True?。沙箱模式見(jiàn)文檔中的SandboxedEnvironment?。
該環(huán)境的過(guò)濾器字典。只要沒(méi)有加載過(guò)模板,添加新過(guò)濾器或刪除舊的都是 安全的。自定義過(guò)濾器見(jiàn)?自定義過(guò)濾器?。有效的過(guò)濾器名稱(chēng)見(jiàn)?標(biāo)識(shí)符的說(shuō)明?。
該環(huán)境的測(cè)試函數(shù)字典。只要沒(méi)有加載過(guò)模板,修改這個(gè)字典都是安全的。 自定義測(cè)試見(jiàn) see?自定義測(cè)試?。有效的測(cè)試名見(jiàn)?標(biāo)識(shí)符的說(shuō)明?。
一個(gè)全局變量字典。這些變量在模板中總是可用。只要沒(méi)有加載過(guò)模板,修 改這個(gè)字典都是安全的。更多細(xì)節(jié)見(jiàn)?全局命名空間?。有效的 對(duì)象名見(jiàn)?標(biāo)識(shí)符的說(shuō)明。
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])
為?name?創(chuàng)建一個(gè)新?Undefined?對(duì)象。這對(duì)可能為某些操作返回 未定義對(duì)象過(guò)濾器和函數(shù)有用。除了?hint?,為了良好的可讀性,所有參數(shù) 應(yīng)該作為關(guān)鍵字參數(shù)傳入。如果提供了?hint?,它被用作異常的錯(cuò)誤消息, 否則錯(cuò)誤信息會(huì)由?obj?和name?自動(dòng)生成。?exc?為生成未定義對(duì)象而 不允許未定義的對(duì)象時(shí)拋出的異常。默認(rèn)的異常是?UndefinedError?。 如果提供了?hint?,?name?會(huì)被發(fā)送。
創(chuàng)建一個(gè)未定義對(duì)象的最常用方法是只提供名稱(chēng):
return environment.undefined(name='some_name')
這意味著名稱(chēng)?some_name?未被定義。如果名稱(chēng)來(lái)自一個(gè)對(duì)象的屬性,把 持有它的對(duì)象告知未定義對(duì)象對(duì)豐富錯(cuò)誤消息很有意義:
if not hasattr(obj, 'attr'):
return environment.undefined(obj=obj, name='attr')
更復(fù)雜的例子中,你可以提供一個(gè) hint 。例如?first()?過(guò)濾器 用這種方法創(chuàng)建一個(gè)未定義對(duì)象:
return environment.undefined('no first item, sequence was empty')
如果?name?或?obj?是已知的(比如訪問(wèn)了了一個(gè)屬性),它應(yīng)該傳遞給 未定義對(duì)象,即使提供了自定義的?hint?。這讓未定義對(duì)象有可能增強(qiáng)錯(cuò)誤 消息。
Adds an extension after the environment was created.
New in version 2.5.
compile_expression(source,?undefined_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(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 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.
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(source,?globals=None,?template_class=None)
Load a template from a string. This parses the source given and returns aTemplate?object.
get_or_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 to?get_template().
New in version 2.3.
get_template(name,?parent=None,?globals=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 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)
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)
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.
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
該模板的全局變量字典。修改這個(gè)字典是不安全的,因?yàn)樗赡芘c其它模板或 加載這個(gè)模板的環(huán)境共享。
模板的加載名。如果模板從字符串加載,這個(gè)值為?None?。
模板在文件系統(tǒng)上的文件名,如果沒(méi)有從文件系統(tǒng)加載,這個(gè)值為?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:
template.render(knights='that say nih')
template.render({'knights': 'that say nih'})
This will return the rendered template as unicode string.
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().
Works exactly like?generate()?but returns a?TemplateStream.
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.
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 the output buffering.
dump(fp,?encoding=None,?errors='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.
更多建議: