高層 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.
- 介紹
- 預備知識
- 安裝
- 基本 API 使用
- 實驗性的 Python 3 支持
- API
- 基礎
- Unicode
- 高層 API
- 自動轉義
- 標識符的說明
- 未定義類型
- 上下文
- 加載器
- 字節碼緩存
- 實用工具
- 異常
- 自定義過濾器
- 求值上下文
- 自定義測試
- 全局命名空間
- 低層 API
- 元 API
- 沙箱
- API
- 運算符攔截
- 模板設計者文檔
- 概要
- 變量
- 過濾器
- 測試
- 注釋
- 空白控制
- 轉義
- 行語句
- 模板繼承
- HTML 轉義
- 控制結構清單
- 導入上下文行為
- 表達式
- 內置過濾器清單
- 內置測試清單
- 全局函數清單
- 擴展
- 自動轉義擴展
- 擴展
- 添加擴展
- i18n 擴展
- 表達式語句
- 循環控制
- With 語句
- 自動轉義擴展
- 編寫擴展
- 集成
- Babel 集成
- Pylons
- TextMate
- Vim
- 從其它的模板引擎切換
- Jinja1
- Django
- Mako
- 提示和技巧
- Null-Master 退回
- 交替的行
- 高亮活動菜單項
- 訪問父級循環