Jinja2 支持?jǐn)U展來(lái)添加過(guò)濾器、測(cè)試、全局變量或者甚至是處理器。擴(kuò)展的主要?jiǎng)恿κ?把諸如添加國(guó)際化支持的常用代碼遷移到一個(gè)可重用的類(lèi)。
擴(kuò)展在 Jinja2 環(huán)境創(chuàng)建時(shí)被添加。一旦環(huán)境被創(chuàng)建,就不能添加額外的擴(kuò)展。要添加 一個(gè)擴(kuò)展,傳遞一個(gè)擴(kuò)展類(lèi)或?qū)肼窂降牧斜淼?Environment 構(gòu)造函數(shù)的 environment 參數(shù)。下面的例子創(chuàng)建了一個(gè)加載了 i18n 擴(kuò)展的 Jinja2 環(huán)境:
jinja_env = Environment(extensions=['jinja2.ext.i18n'])
Import name: jinja2.ext.i18n
Jinja2 當(dāng)前只附帶一個(gè)擴(kuò)展,就是 i18n 擴(kuò)展。它可以與 [gettext][1] 或 [babel][2] 聯(lián)合使用。如果啟用了 i18n 擴(kuò)展, Jinja2 提供了 trans 語(yǔ)句來(lái)標(biāo)記被其包裹的 字符串為可翻譯的,并調(diào)用 gettext 。
在啟用虛擬的 _ 函數(shù)后,之后的 gettext 調(diào)用會(huì)被添加到環(huán)境的全局變量。那么 一個(gè)國(guó)際化的應(yīng)用應(yīng)該不僅在全局,以及在每次渲染中在命名空間中提供至少一個(gè) gettext 或可選的 ngettext 函數(shù)。
在啟用這個(gè)擴(kuò)展后,環(huán)境提供下面的額外方法:
jinja2.Environment.``install_gettext_translations(translations, newstyle=False)在該環(huán)境中全局安裝翻譯。提供的翻譯對(duì)象要至少實(shí)現(xiàn) uggettext 和 ungettext 。 gettext.NullTranslations 和 gettext.GNUTranslations 類(lèi)和 [Babel][2]'s 的 Translations 類(lèi)也被支持。
Changed in version 2.5: 添加了新樣式的 gettext
jinja2.Environment.``install_null_translations(newstyle=False)安裝虛擬的 gettext 函數(shù)。這在你想使應(yīng)用為國(guó)際化做準(zhǔn)備但還不想實(shí)現(xiàn)完整的 國(guó)際化系統(tǒng)時(shí)很有用。
Changed in version 2.5: 添加了新樣式的 gettext
jinja2.Environment.``install_gettext_callables(gettext, ngettext, newstyle=False)在環(huán)境中把給出的 gettext 和 ngettext 可調(diào)用量安裝為全局變量。它們 應(yīng)該表現(xiàn)得幾乎與標(biāo)準(zhǔn)庫(kù)中的 gettext.ugettext() 和 gettext.ungettext() 函數(shù)相同。
如果激活了 新樣式 ,可調(diào)用量被包裝為新樣式的可調(diào)用量一樣工作。更多 信息見(jiàn) 新樣式 Gettext 。
New in version 2.5.
jinja2.Environment.uninstall_gettext_translations()
再次卸載翻譯。
jinja2.Environment.extract_translations(source)
從給定的模板或源中提取本地化字符串。
對(duì)找到的每一個(gè)字符串,這個(gè)函數(shù)生產(chǎn)一個(gè) (lineno, function, message ) 元組,在這里:
如果安裝了 Babel , Babel 集成 可以用來(lái)為 babel 抽取字符串。
對(duì)于一個(gè)對(duì)多種語(yǔ)言可用而對(duì)所有用戶給出同一種的語(yǔ)言的 web 應(yīng)用(例如一個(gè)法國(guó)社 區(qū)安全了一個(gè)多種語(yǔ)言的論壇軟件)可能會(huì)一次性加載翻譯并且在環(huán)境生成時(shí)把翻譯方 法添加到環(huán)境上:
translations = get_gettext_translations()
env = Environment(extensions=['jinja2.ext.i18n'])
env.install_gettext_translations(translations)
get_get_translations 函數(shù)會(huì)返回當(dāng)前配置的翻譯器。(比如使用 gettext.find )
模板設(shè)計(jì)者的 i18n 擴(kuò)展使用在 模板文檔中有描述。
從版本 2.5 開(kāi)始你可以使用新樣式的 gettext 調(diào)用。這些的啟發(fā)源于 trac 的內(nèi)部 gettext 函數(shù)并且完全被 babel 抽取工具支持。如果你不使用 Babel 的抽取工具, 它可能不會(huì)像其它抽取工具預(yù)期的那樣工作。
標(biāo)準(zhǔn) gettext 調(diào)用和新樣式的 gettext 調(diào)用有什么區(qū)別?通常,它們要輸入的東西 更少,出錯(cuò)率更低。并且如果在自動(dòng)轉(zhuǎn)義環(huán)境中使用它們,它們也能更好地支持自動(dòng) 轉(zhuǎn)義。這里是一些新老樣式調(diào)用的差異:
標(biāo)準(zhǔn) gettext:
{{ gettext('Hello World!') }}
{{ gettext('Hello %(name)s!')|format(name='World') }}
{{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
num=apples|count
)}}
新樣式看起來(lái)是這樣:
{{ gettext('Hello World!') }}
{{ gettext('Hello %(name)s!', name='World') }}
{{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
新樣式 gettext 的優(yōu)勢(shì)是你需要輸入的更少,并且命名占位符是強(qiáng)制的。后者看起 來(lái)似乎是缺陷,但解決了當(dāng)翻譯者不能切換兩個(gè)占位符的位置時(shí)經(jīng)常勉勵(lì)的一大堆 麻煩。使用新樣式的 gettext ,所有的格式化字符串看起來(lái)都一樣。
除此之外,在新樣式 gettext 中,如果沒(méi)有使用占位符,字符串格式化也會(huì)被使用, 這使得所有的字符串表現(xiàn)一致。最后,不僅是新樣式的 gettext 調(diào)用可以妥善地為 解決了許多轉(zhuǎn)義相關(guān)問(wèn)題的自動(dòng)轉(zhuǎn)義標(biāo)記字符串,許多模板也在使用自動(dòng)轉(zhuǎn)義時(shí)體驗(yàn) 了多次。
Import name: jinja2.ext.do
“do”又叫做表達(dá)式語(yǔ)句擴(kuò)展,向模板引擎添加了一個(gè)簡(jiǎn)單的 do 標(biāo)簽,其工作如同 一個(gè)變量表達(dá)式,只是忽略返回值。
Import name: jinja2.ext.loopcontrols
這個(gè)擴(kuò)展添加了循環(huán)中的 break 和 continue 支持。在啟用它之后, Jinja2 提供的這兩個(gè)關(guān)鍵字如同 Python 中那樣工作。
Import name: jinja2.ext.with_
New in version 2.3.
這個(gè)擴(kuò)展添加了 with 關(guān)鍵字支持。使用這個(gè)關(guān)鍵字可以在模板中強(qiáng)制一塊嵌套的 作用域。變量可以在 with 語(yǔ)句的塊頭中直接聲明,或直接在里面使用標(biāo)準(zhǔn)的 set 語(yǔ)句。
Import name: jinja2.ext.autoescape
New in version 2.4.
自動(dòng)轉(zhuǎn)義擴(kuò)展允許你在模板內(nèi)開(kāi)關(guān)自動(dòng)轉(zhuǎn)義特性。如果環(huán)境的 autoescape 設(shè)定為 False ,它可以被激活。如果是 True 可以被關(guān)閉。這個(gè)設(shè)定的覆蓋是有作用域的。
你可以編寫(xiě)擴(kuò)展來(lái)向 Jinja2 中添加自定義標(biāo)簽。這是一個(gè)不平凡的任務(wù),而且通常不需 要,因?yàn)槟J(rèn)的標(biāo)簽和表達(dá)式涵蓋了所有常用情況。如 i18n 擴(kuò)展是一個(gè)擴(kuò)展有用的好例 子,而另一個(gè)會(huì)是碎片緩存。
當(dāng)你編寫(xiě)擴(kuò)展時(shí),你需要記住你在與 Jinja2 模板編譯器一同工作,而它并不驗(yàn)證你傳遞 到它的節(jié)點(diǎn)樹(shù)。如果 AST 是畸形的,你會(huì)得到各種各樣的編譯器或運(yùn)行時(shí)錯(cuò)誤,這調(diào)試起 來(lái)極其可怕。始終確保你在使用創(chuàng)建正確的節(jié)點(diǎn)。下面的 API 文檔展示了有什么節(jié)點(diǎn)和如 何使用它們。
下面的例子用 Werkzeug 的緩存 contrib 模塊為 Jinja2 實(shí)現(xiàn)了一個(gè) cache 標(biāo)簽:
from jinja2 import nodes
from jinja2.ext import Extension
class FragmentCacheExtension(Extension):
# a set of names that trigger the extension.
tags = set(['cache'])
def __init__(self, environment):
super(FragmentCacheExtension, self).__init__(environment)
# add the defaults to the environment
environment.extend(
fragment_cache_prefix='',
fragment_cache=None
)
def parse(self, parser):
# the first token is the token that started the tag. In our case
# we only listen to ``'cache'`` so this will be a name token with
# `cache` as value. We get the line number so that we can give
# that line number to the nodes we create by hand.
lineno = parser.stream.next().lineno
# now we parse a single expression that is used as cache key.
args = [parser.parse_expression()]
# if there is a comma, the user provided a timeout. If not use
# None as second parameter.
if parser.stream.skip_if('comma'):
args.append(parser.parse_expression())
else:
args.append(nodes.Const(None))
# now we parse the body of the cache block up to `endcache` and
# drop the needle (which would always be `endcache` in that case)
body = parser.parse_statements(['name:endcache'], drop_needle=True)
# now return a `CallBlock` node that calls our _cache_support
# helper method on this extension.
return nodes.CallBlock(self.call_method('_cache_support', args),
[], [], body).set_lineno(lineno)
def _cache_support(self, name, timeout, caller):
"""Helper callback."""
key = self.environment.fragment_cache_prefix + name
# try to load the block from the cache
# if there is no fragment in the cache, render it and store
# it in the cache.
rv = self.environment.fragment_cache.get(key)
if rv is not None:
return rv
rv = caller()
self.environment.fragment_cache.add(key, rv, timeout)
return rv
而這是你在環(huán)境中使用它的方式:
from jinja2 import Environment
from werkzeug.contrib.cache import SimpleCache
env = Environment(extensions=[FragmentCacheExtension])
env.fragment_cache = SimpleCache()
之后,在模板中可以標(biāo)記塊為可緩存的。下面的例子緩存一個(gè)邊欄 300 秒:
{% cache 'sidebar', 300 %}
<div class="sidebar">
...
</div>
{% endcache %}
擴(kuò)展總是繼承 jinja2.ext.Extension 類(lèi):
class jinja2.ext.Extension(environment) Extensions can be used to add extra functionality to the Jinja template system at the parser level. Custom extensions are bound to an environment but may not store environment specific data on self. The reason for this is that an extension can be bound to another environment (for overlays) by creating a copy and reassigning the environment attribute.
As extensions are created by the environment they cannot accept any arguments for configuration. One may want to work around that by using a factory function, but that is not possible as extensions are identified by their import name. The correct way to configure the extension is storing the configuration values on the environment. Because this way the environment ends up acting as central configuration storage the attributes may clash which is why extensions have to ensure that the names they choose for configuration are not too generic. prefix for example is a terrible name, fragment_cache_prefix on the other hand is a good name as includes the name of the extension (fragment cache).
identifier 擴(kuò)展的標(biāo)識(shí)符。這始終是擴(kuò)展類(lèi)的真實(shí)導(dǎo)入名,不能被修改。
tags 如果擴(kuò)展實(shí)現(xiàn)自定義標(biāo)簽,這是擴(kuò)展監(jiān)聽(tīng)的標(biāo)簽名的集合。
attr(name, lineno=None) Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code.
self.attr('_my_attribute', lineno=lineno)
call_method(name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None) Call a method of the extension. This is a shortcut for attr() + jinja2.nodes.Call.
filter_stream(stream) It’s passed a TokenStream that can be used to filter tokens returned. This method has to return an iterable of Tokens, but it doesn’t have to return a TokenStream.
In the ext folder of the Jinja2 source distribution there is a file called inlinegettext.py which implements a filter that utilizes this method.
parse(parser) If any of the tags matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
preprocess(source, name, filename=None) This method is called before the actual lexing and can be used to preprocess the source. The filename is optional. The return value must be the preprocessed source.
傳遞到 Extension.parse() 的解析器提供解析不同類(lèi)型表達(dá)式的方式。下 面的方法可能會(huì)在擴(kuò)展中使用:
class jinja2.parser.Parser(environment, source, name=None, filename=None, state=None) This is the central parsing class Jinja2 uses. It’s passed to extensions and can be used to parse expressions or statements.
filename
解析器處理的模板文件名。這 不是 模板的加載名。加載名見(jiàn) name 。對(duì)于不是從文件系統(tǒng)中加載的模板,這個(gè)值為 None 。
name
模板的加載名。
stream
當(dāng)前的 TokenStream 。
fail(msg, lineno=None, exc=<class
'jinja2.exceptions.TemplateSyntaxError'>)
Convenience method that raises exc with the message, passed line number or last line number as well as the current name and filename.
free_identifier(lineno=None)
Return a new free identifier as InternalName.
parse_assign_target(with_tuple=True, name_only=False, extra_end_rules=None)
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting with_tuple to False. If only assignments to names are wanted name_only can be set to True. The extra_end_rules parameter is forwarded to the tuple parsing function.
parse_expression(with_condexpr=True)
Parse an expression. Per default all expressions are parsed, if the optional with_condexpr parameter is set to False conditional expressions are not parsed.
parse_statements(end_tokens, drop_needle=False)
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the end_tokens is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted drop_needle can be set to True and the end token is removed.
parse_tuple(simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False)
Works like parse_expression but if multiple expressions are delimited by a comma a Tuple node is created. This method could also return a regular expression instead of a tuple if no commas where found.
The default parsing mode is a full tuple. If simplified is True only names and literals are parsed. The no_condexpr parameter is forwarded to parse_expression().
Because tuples do not require delimiters and may end in a bogus comma an extra hint is needed that marks the end of a tuple. For example for loops support tuples between for and in. In that case the extra_end_rules is set to ['name:in'].
explicit_parentheses is true if the parsing was triggered by an expression in parentheses. This is used to figure out if an empty tuple is a valid expression or not.
class jinja2.lexer.TokenStream(generator, name, filename) A token stream is an iterable that yields Tokens. The parser however does not iterate over it but calls next() to go one token ahead. The current active token is stored as current.
current
當(dāng)前的 Token 。
eos
Are we at the end of the stream?
expect(expr)
Expect a given token type and return it. This accepts the same argument as jinja2.lexer.Token.test().
look()
Look at the next token.
next()
Go one token ahead and return the old one
next_if(expr)
Perform the token test and return the token if it matched. Otherwise the return value is None.
push(token)
Push a token back to the stream.
skip(n=1)
Got n tokens ahead.
skip_if(expr)
Like next_if() but only returns True or False.
class jinja2.lexer.Token Token class.
lineno
token 的行號(hào)。
type
token 的類(lèi)型。這個(gè)值是被禁錮的,所以你可以用 is 運(yùn)算符同任意字符 串比較。
value
token 的值。
test(expr)
Test a token against a token expression. This can either be a token type or 'token_type:token_value'. This can only test against string values and types.
test_any(*iterable)
Test against multiple token expressions.
同樣,在詞法分析模塊中也有一個(gè)實(shí)用函數(shù)可以計(jì)算字符串中的換行符數(shù)目:
.. autofunction:: jinja2.lexer.count_newlines
AST(抽象語(yǔ)法樹(shù): Abstract Syntax Tree)用于表示解析后的模板。它有編譯器之后 轉(zhuǎn)換到可執(zhí)行的 Python 代碼對(duì)象的節(jié)點(diǎn)構(gòu)建。提供自定義語(yǔ)句的擴(kuò)展可以返回執(zhí)行自 定義 Python 代碼的節(jié)點(diǎn)。
下面的清單展示了所有當(dāng)前可用的節(jié)點(diǎn)。 AST 在 Jinja2 的各個(gè)版本中有差異,但會(huì)向 后兼容。
更多信息請(qǐng)見(jiàn) jinja2.Environment.parse()。
class jinja2.nodes.Node
Baseclass for all Jinja2 nodes. There are a number of nodes available of different types. There are four major types:
All nodes have fields and attributes. Fields may be other nodes, lists, or arbitrary values. Fields are passed to the constructor as regular positional arguments, attributes as keyword arguments. Each node has two attributes: lineno (the line number of the node) and environment. The environment attribute is set at the end of the parsing process for all nodes automatically.
find(node_type)
Find the first node of a given type. If no such node exists the return value is None.
find_all(node_type)
Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.
iter_child_nodes(exclude=None, only=None)
Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned.
iter_fields(exclude=None, only=None)
This method iterates over all fields that are defined and yields (key, value) tuples. Per default all fields are returned, but it’s possible to limit that to some fields by providing the only parameter or to exclude some using the exclude parameter. Both should be sets or tuples of field names.
set_ctx(ctx)
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a ‘load’ context as it’s the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
set_environment(environment)
Set the environment for all nodes.
set_lineno(lineno, override=False)
Set the line numbers of the node and children.
class jinja2.nodes.Expr
Baseclass for all expressions.
Node type: Node as_const(eval_ctx=None) Return the value of the expression as constant or raise Impossible if this was not possible.
An EvalContext can be provided, if none is given a default context is created which requires the nodes to have an attached environment.
Changed in version 2.4: the eval_ctx parameter was added.
can_assign() Check if it’s possible to assign something to this node.
class jinja2.nodes.BinExpr(left, right) Baseclass for all binary expressions.
Node type: Expr class jinja2.nodes.Add(left, right) Add the left to the right node.
Node type: BinExpr class jinja2.nodes.And(left, right) Short circuited AND.
Node type: BinExpr class jinja2.nodes.Div(left, right) Divides the left by the right node.
Node type: BinExpr class jinja2.nodes.FloorDiv(left, right) Divides the left by the right node and truncates conver the result into an integer by truncating.
Node type: BinExpr class jinja2.nodes.Mod(left, right) Left modulo right.
Node type: BinExpr class jinja2.nodes.Mul(left, right) Multiplies the left with the right node.
Node type: BinExpr class jinja2.nodes.Or(left, right) Short circuited OR.
Node type: BinExpr class jinja2.nodes.Pow(left, right) Left to the power of right.
Node type: BinExpr class jinja2.nodes.Sub(left, right) Substract the right from the left node.
Node type: BinExpr class jinja2.nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs) Calls an expression. args is a list of arguments, kwargs a list of keyword arguments (list of Keyword nodes), and dyn_args and dyn_kwargs has to be either None or a node that is used as node for dynamic positional (*args) or keyword (**kwargs) arguments.
Node type: Expr class jinja2.nodes.Compare(expr, ops) Compares an expression with some other expressions. ops must be a list of Operands.
Node type: Expr class jinja2.nodes.Concat(nodes) Concatenates the list of expressions provided after converting them to unicode.
Node type: Expr class jinja2.nodes.CondExpr(test, expr1, expr2) A conditional expression (inline if expression). ({{ foo if bar else baz }})
Node type: Expr class jinja2.nodes.ContextReference Returns the current template context. It can be used like a Name node, with a 'load' ctx and will return the current Context object.
Here an example that assigns the current template name to a variable named foo:
Assign(Name('foo', ctx='store'), Getattr(ContextReference(), 'name')) Node type: Expr class jinja2.nodes.EnvironmentAttribute(name) Loads an attribute from the environment object. This is useful for extensions that want to call a callback stored on the environment.
Node type: Expr class jinja2.nodes.ExtensionAttribute(identifier, name) Returns the attribute of an extension bound to the environment. The identifier is the identifier of the Extension.
This node is usually constructed by calling the attr() method on an extension.
Node type: Expr class jinja2.nodes.Filter(node, name, args, kwargs, dyn_args, dyn_kwargs) This node applies a filter on an expression. name is the name of the filter, the rest of the fields are the same as for Call.
If the node of a filter is None the contents of the last buffer are filtered. Buffers are created by macros and filter blocks.
Node type: Expr class jinja2.nodes.Getattr(node, attr, ctx) Get an attribute or item from an expression that is a ascii-only bytestring and prefer the attribute.
Node type: Expr class jinja2.nodes.Getitem(node, arg, ctx) Get an attribute or item from an expression and prefer the item.
Node type: Expr class jinja2.nodes.ImportedName(importname) If created with an import name the import name is returned on node access. For example ImportedName('cgi.escape') returns the escape function from the cgi module on evaluation. Imports are optimized by the compiler so there is no need to assign them to local variables.
Node type: Expr class jinja2.nodes.InternalName(name) An internal name in the compiler. You cannot create these nodes yourself but the parser provides a free_identifier() method that creates a new identifier for you. This identifier is not available from the template and is not threated specially by the compiler.
Node type: Expr class jinja2.nodes.Literal Baseclass for literals.
Node type: Expr class jinja2.nodes.Const(value) All constant values. The parser will return this node for simple constants such as 42 or "foo" but it can be used to store more complex values such as lists too. Only constants with a safe representation (objects where eval(repr(x)) == x is true).
Node type: Literal class jinja2.nodes.Dict(items) Any dict literal such as {1: 2, 3: 4}. The items must be a list of Pair nodes.
Node type: Literal class jinja2.nodes.List(items) Any list literal such as [1, 2, 3]
Node type: Literal class jinja2.nodes.TemplateData(data) A constant template string.
Node type: Literal class jinja2.nodes.Tuple(items, ctx) For loop unpacking and some other things like multiple arguments for subscripts. Like for Name ctx specifies if the tuple is used for loading the names or storing.
Node type: Literal class jinja2.nodes.MarkSafe(expr) Mark the wrapped expression as safe (wrap it as Markup).
Node type: Expr class jinja2.nodes.MarkSafeIfAutoescape(expr) Mark the wrapped expression as safe (wrap it as Markup) but only if autoescaping is active.
New in version 2.5.
Node type: Expr class jinja2.nodes.Name(name, ctx) Looks up a name or stores a value in a name. The ctx of the node can be one of the following values:
store: store a value in the name load: load that name param: like store but if the name was defined as function parameter. Node type: Expr class jinja2.nodes.Slice(start, stop, step) Represents a slice object. This must only be used as argument for Subscript.
Node type: Expr class jinja2.nodes.Test(node, name, args, kwargs, dyn_args, dyn_kwargs) Applies a test on an expression. name is the name of the test, the rest of the fields are the same as for Call.
Node type: Expr class jinja2.nodes.UnaryExpr(node) Baseclass for all unary expressions.
Node type: Expr class jinja2.nodes.Neg(node) Make the expression negative.
Node type: UnaryExpr class jinja2.nodes.Not(node) Negate the expression.
Node type: UnaryExpr class jinja2.nodes.Pos(node) Make the expression positive (noop for most expressions)
Node type: UnaryExpr class jinja2.nodes.Helper Nodes that exist in a specific context only.
Node type: Node class jinja2.nodes.Keyword(key, value) A key, value pair for keyword arguments where key is a string.
Node type: Helper class jinja2.nodes.Operand(op, expr) Holds an operator and an expression. The following operators are available: %, *, , +, -, //, /, eq, gt, gteq, in, lt, lteq, ne, not, notin
Node type: Helper class jinja2.nodes.Pair(key, value) A key, value pair for dicts.
Node type: Helper class jinja2.nodes.Stmt Base node for all statements.
Node type: Node class jinja2.nodes.Assign(target, node) Assigns an expression to a target.
Node type: Stmt class jinja2.nodes.Block(name, body, scoped) A node that represents a block.
Node type: Stmt class jinja2.nodes.Break Break a loop.
Node type: Stmt class jinja2.nodes.CallBlock(call, args, defaults, body) Like a macro without a name but a call instead. call is called with the unnamed macro as caller argument this node holds.
Node type: Stmt class jinja2.nodes.Continue Continue a loop.
Node type: Stmt class jinja2.nodes.EvalContextModifier(options) Modifies the eval context. For each option that should be modified, a Keyword has to be added to the options list.
Example to change the autoescape setting:
EvalContextModifier(options=[Keyword('autoescape', Const(True))]) Node type: Stmt class jinja2.nodes.ScopedEvalContextModifier(options, body) Modifies the eval context and reverts it later. Works exactly like EvalContextModifier but will only modify the EvalContext for nodes in the body.
Node type: EvalContextModifier class jinja2.nodes.ExprStmt(node) A statement that evaluates an expression and discards the result.
Node type: Stmt class jinja2.nodes.Extends(template) Represents an extends statement.
Node type: Stmt class jinja2.nodes.FilterBlock(body, filter) Node for filter sections.
Node type: Stmt class jinja2.nodes.For(target, iter, body, else, test, recursive) The for loop. target is the target for the iteration (usually a Name or Tuple), iter the iterable. body is a list of nodes that are used as loop-body, and else a list of nodes for the else block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as test, otherwise None.
Node type: Stmt class jinja2.nodes.FromImport(template, names, with_context) A node that represents the from import tag. It’s important to not pass unsafe names to the name attribute. The compiler translates the attribute lookups directly into getattr calls and does not use the subscript callback of the interface. As exported variables may not start with double underscores (which the parser asserts) this is not a problem for regular Jinja code, but if this node is used in an extension extra care must be taken.
The list of names may contain tuples if aliases are wanted.
Node type: Stmt class jinja2.nodes.If(test, body, else) If test is true, body is rendered, else else.
Node type: Stmt class jinja2.nodes.Import(template, target, with_context) A node that represents the import tag.
Node type: Stmt class jinja2.nodes.Include(template, with_context, ignore_missing) A node that represents the include tag.
Node type: Stmt class jinja2.nodes.Macro(name, args, defaults, body) A macro definition. name is the name of the macro, args a list of arguments and defaults a list of defaults if there are any. body is a list of nodes for the macro body.
Node type: Stmt class jinja2.nodes.Output(nodes) A node that holds multiple expressions which are then printed out. This is used both for the print statement and the regular template data.
Node type: Stmt class jinja2.nodes.Scope(body) An artificial scope.
Node type: Stmt class jinja2.nodes.Template(body) Node that represents a template. This must be the outermost node that is passed to the compiler.
Node type: Node exception jinja2.nodes.Impossible? Raised if the node could not perform a requested action.