Extensions¶

Jinja2 supports extensions that can add extra filters, tests, globals or evenextend the parser. The main motivation of extensions is to move often usedcode into a reusable class like adding support for internationalization.

Adding Extensions¶

Extensions are added to the Jinja2 environment at creation time. Once theenvironment is created additional extensions cannot be added. To add anextension pass a list of extension classes or import paths to theextensions parameter of the Environment constructor. The followingexample creates a Jinja2 environment with the i18n extension loaded:

  1. jinja_env = Environment(extensions=['jinja2.ext.i18n'])

i18n Extension¶

Import name:jinja2.ext.i18n

The i18n extension can be used in combination with gettext or babel. Ifthe i18n extension is enabled Jinja2 provides a trans statement that marksthe wrapped string as translatable and calls gettext.

After enabling, dummy __ function that forwards calls to _gettext is addedto the environment globals. An internationalized application then has toprovide a gettext function and optionally an ngettext function into thenamespace, either globally or for each rendering.

Environment Methods¶

After enabling the extension, the environment provides the followingadditional methods:

jinja2.Environment.installgettext_translations(_translations, newstyle=False)

Installs a translation globally for that environment. The translationsobject provided must implement at least ugettext and ungettext.The gettext.NullTranslations and gettext.GNUTranslations classesas well as Babels Translations class are supported.


Changed in version 2.5: newstyle gettext added

jinja2.Environment.installnull_translations(_newstyle=False)

Install dummy gettext functions. This is useful if you want to preparethe application for internationalization but don’t want to implement thefull internationalization system yet.


Changed in version 2.5: newstyle gettext added

jinja2.Environment.installgettext_callables(_gettext, ngettext, newstyle=False)
Installs the given gettext and ngettext callables into theenvironment as globals. They are supposed to behave exactly like thestandard library’s gettext.ugettext() andgettext.ungettext() functions.

If newstyle is activated, the callables are wrapped to work likenewstyle callables. See Whitespace Trimming for more information.


New in version 2.5.

jinja2.Environment.uninstallgettext_translations()

Uninstall the translations again.
jinja2.Environment.extract_translations(_source)

Extract localizable strings from the given template node or source.

For every string found this function yields a (lineno, function,
message)
tuple, where:

- lineno is the number of the line on which the string was found,
- function is the name of the gettext function used (if thestring was extracted from embedded Python code), and
- message is the string itself (a unicode object, or a tupleof unicode objects for functions with multiple string arguments).
If Babel is installed, the babel integrationcan be used to extract strings for babel.

For a web application that is available in multiple languages but gives allthe users the same language (for example a multilingual forum softwareinstalled for a French community) may load the translations once and add thetranslation methods to the environment at environment generation time:



  1. translations = getgettext_translations()
    env = Environment(extensions=['jinja2.ext.i18n'])
    env.install_gettext_translations(translations)




The _get_gettext_translations
function would return the translator for thecurrent configuration. (For example by using gettext.find)

The usage of the i18n extension for template designers is covered as partof the template documentation.



### Whitespace Trimming¶


New in version 2.10.


Linebreaks and surrounding whitespace can be automatically trimmed by enablingthe ext.i18n.trimmed policy.



### Newstyle Gettext¶


New in version 2.5.


Starting with version 2.5 you can use newstyle gettext calls. These areinspired by trac’s internal gettext functions and are fully supported bythe babel extraction tool. They might not work as expected by otherextraction tools in case you are not using Babel’s.

What’s the big difference between standard and newstyle gettext calls? Ingeneral they are less to type and less error prone. Also if they are usedin an autoescaping environment they better support automatic escaping.Here are some common differences between old and new calls:

standard gettext:



  1. {{ gettext('Hello World!') }}
    {{ gettext('Hello %(name)s!')|format(name='World') }}
    {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
    num=apples|count
    )}}




newstyle gettext looks like this instead:



  1. {{ gettext('Hello World!') }}
    {{ gettext('Hello %(name)s!', name='World') }}
    {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}




The advantages of newstyle gettext are that you have less to type and thatnamed placeholders become mandatory. The latter sounds like adisadvantage but solves a lot of troubles translators are often facingwhen they are unable to switch the positions of two placeholder. Withnewstyle gettext, all format strings look the same.

Furthermore with newstyle gettext, string formatting is also used if noplaceholders are used which makes all strings behave exactly the same.Last but not least are newstyle gettext calls able to properly markstrings for autoescaping which solves lots of escaping related issues manytemplates are experiencing over time when using autoescaping.




## Expression Statement¶

Import name:jinja2.ext.do

The “do” aka expression-statement extension adds a simple do tag to thetemplate engine that works like a variable expression but ignores thereturn value.



## Loop Controls¶

Import name:jinja2.ext.loopcontrols

This extension adds support for break and continue in loops. Afterenabling, Jinja2 provides those two keywords which work exactly like inPython.



## With Statement¶

Import name:jinja2.ext.with__


Changed in version 2.9.


This extension is now built-in and no longer does anything.



## Autoescape Extension¶

Import name:_jinja2.ext.autoescape



Changed in version 2.9.


This extension was removed and is now built-in. Enabling the extensionno longer does anything.



## Writing Extensions¶

By writing extensions you can add custom tags to Jinja2. This is a non-trivialtask and usually not needed as the default tags and expressions cover allcommon use cases. The i18n extension is a good example of why extensions areuseful. Another one would be fragment caching.

When writing extensions you have to keep in mind that you are working with theJinja2 template compiler which does not validate the node tree you are passingto it. If the AST is malformed you will get all kinds of compiler or runtimeerrors that are horrible to debug. Always make sure you are using the nodesyou create correctly. The API documentation below shows which nodes exist andhow to use them.


### Example Extension¶

The following example implements a cache tag for Jinja2 by using theWerkzeug caching contrib module:



  1. 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(
    fragmentcache_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 = next(parser.stream).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




And here is how you use it in an environment:



  1. from jinja2 import Environment
    from werkzeug.contrib.cache import SimpleCache

    env = Environment(extensions=[FragmentCacheExtension])
    env.fragment_cache = SimpleCache()




Inside the template it’s then possible to mark blocks as cacheable. Thefollowing example caches a sidebar for 300 seconds:



  1. {% cache 'sidebar', 300 %}
    <div class="sidebar">

    </div>
    {% endcache %}






### Extension API¶

Extensions always have to extend the jinja2.ext.Extension class:
_class jinja2.ext.Extension(environment)

Extensions can be used to add extra functionality to the Jinja templatesystem at the parser level. Custom extensions are bound to an environmentbut may not store environment specific data on self. The reason forthis is that an extension can be bound to another environment (foroverlays) by creating a copy and reassigning the environment attribute.

As extensions are created by the environment they cannot accept anyarguments for configuration. One may want to work around that by usinga factory function, but that is not possible as extensions are identifiedby their import name. The correct way to configure the extension isstoring the configuration values on the environment. Because this way theenvironment ends up acting as central configuration storage theattributes may clash which is why extensions have to ensure that the namesthey choose for configuration are not too generic. prefix for exampleis a terrible name, fragmentcache_prefix on the other hand is a goodname as includes the name of the extension (fragment cache).
identifier

The identifier of the extension. This is always the true import nameof the extension class and must not be changed.
tags

If the extension implements custom tags this is a set of tag namesthe extension is listening for.
attr(_name, lineno=None)

Return an attribute node for the current extension. This is usefulto pass constants on extensions to generated template code.



  1. 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 forattr() + jinja2.nodes.Call.
filterstream(_stream)

It’s passed a TokenStream that can be usedto filter tokens returned. This method has to return an iterable ofTokens, but it doesn’t have to return aTokenStream.

In the ext folder of the Jinja2 source distribution there is a filecalled inlinegettext.py which implements a filter that utilizes thismethod.
parse(parser)

If any of the tags matched this method is called with theparser as first argument. The token the parser stream is pointing atis the name token that matched. This method has to return one or alist of multiple nodes.
preprocess(source, name, filename=None)

This method is called before the actual lexing and can be used topreprocess the source. The filename is optional. The return valuemust be the preprocessed source.

Parser API¶

The parser passed to Extension.parse() provides ways to parseexpressions of different types. The following methods may be used byextensions:

class jinja2.parser.Parser(environment, source, name=None, filename=None, state=None)

This is the central parsing class Jinja2 uses. It’s passed toextensions and can be used to parse expressions or statements.
filename

The filename of the template the parser processes. This is notthe load name of the template. For the load name see name.For templates that were not loaded form the file system this isNone.
name

The load name of the template.
stream

The current TokenStream
fail(msg, lineno=None, exc=<class 'jinja2.exceptions.TemplateSyntaxError'>)

Convenience method that raises exc with the message, passedline number or last line number as well as the current name andfilename.
freeidentifier(_lineno=None)

Return a new free identifier as InternalName.
parseassign_target(_with_tuple=True, name_only=False, extra_end_rules=None, with_namespace=False)

Parse an assignment target. As Jinja2 allows assignments totuples, this function can parse all allowed assignment targets. Perdefault assignments to tuples are parsed, that can be disable howeverby setting with_tuple to False. If only assignments to names arewanted name_only can be set to True. The extra_end_rules_parameter is forwarded to the tuple parsing function. If_with_namespace is enabled, a namespace assignment may be parsed.
parseexpression(_with_condexpr=True)

Parse an expression. Per default all expressions are parsed, ifthe optional with_condexpr parameter is set to False conditionalexpressions are not parsed.
parsestatements(_end_tokens, drop_needle=False)

Parse multiple statements into a list until one of the end tokensis reached. This is used to parse the body of statements as it alsoparses template data if appropriate. The parser checks first if thecurrent token is a colon and skips it if there is one. Then it checksfor the block end and parses until if one of the end_tokens isreached. Per default the active token in the stream at the end ofthe call is the matched end token. If this is not wanted drop_needle_can be set to _True and the end token is removed.
parsetuple(_simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False)

Works like parse_expression but if multiple expressions aredelimited by a comma a Tuple node is created.This method could also return a regular expression instead of a tupleif 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 isforwarded to parse_expression().

Because tuples do not require delimiters and may end in a bogus commaan extra hint is needed that marks the end of a tuple. For examplefor loops support tuples between for and in. In that case theextra_end_rules is set to ['name:in'].

explicit_parentheses is true if the parsing was triggered by anexpression in parentheses. This is used to figure out if an emptytuple is a valid expression or not.
class jinja2.lexer.TokenStream(generator, name, filename)

A token stream is an iterable that yields Tokens. Theparser however does not iterate over it but calls next() to goone token ahead. The current active token is stored as current.
current

The current Token.
eos

Are we at the end of the stream?
expect(expr)

Expect a given token type and return it. This accepts the sameargument as jinja2.lexer.Token.test().
look()

Look at the next token.
nextif(_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.
skipif(_expr)

Like next_if() but only returns True or False.
class jinja2.lexer.Token

Token class.
lineno

The line number of the token
type

The type of the token. This string is interned so you may compareit with arbitrary strings using the is operator.
value

The value of the token.
test(expr)

Test a token against a token expression. This can either be atoken type or 'tokentype:token_value'. This can only testagainst string values and types.
test_any(*iterable)

Test against multiple token expressions.

There is also a utility function in the lexer module that can count newlinecharacters in strings:
jinja2.lexer.count_newlines(_value)

Count the number of newline characters in the string. This isuseful for extensions that filter a stream.

AST¶

The AST (Abstract Syntax Tree) is used to represent a template after parsing.It’s build of nodes that the compiler then converts into executable Pythoncode objects. Extensions that provide custom statements can return nodes toexecute custom Python code.

The list below describes all nodes that are currently available. The AST maychange between Jinja2 versions but will stay backwards compatible.

For more information have a look at the repr of jinja2.Environment.parse().

class jinja2.nodes.Node

Baseclass for all Jinja2 nodes. There are a number of nodes availableof different types. There are four major types:

- Stmt: statements
- Expr: expressions
- Helper: helper nodes
- Template: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,or arbitrary values. Fields are passed to the constructor as regularpositional arguments, attributes as keyword arguments. Each node hastwo attributes: lineno (the line number of the node) and environment.The environment attribute is set at the end of the parsing process forall nodes automatically.
find(node_type)

Find the first node of a given type. If no such node exists thereturn value is None.
findall(_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.
iterchild_nodes(_exclude=None, only=None)

Iterates over all direct child nodes of the node. This iteratesover all fields and yields the values of they are nodes. If the valueof a field is a list all the nodes in that list are returned.
iterfields(_exclude=None, only=None)

This method iterates over all fields that are defined and yields(key, value) tuples. Per default all fields are returned, butit’s possible to limit that to some fields by providing the only_parameter or to exclude some using the _exclude parameter. Bothshould be sets or tuples of field names.
setctx(_ctx)

Reset the context of a node and all child nodes. Per default theparser will all generate nodes that have a ‘load’ context as it’s themost common one. This method is used in the parser to set assignmenttargets and other nodes to a store context.
setenvironment(_environment)

Set the environment for all nodes.
setlineno(_lineno, override=False)

Set the line numbers of the node and children.
class jinja2.nodes.Expr

Baseclass for all expressions.

|Node type:
|——-
|Node

asconst(_eval_ctx=None)

Return the value of the expression as constant or raiseImpossible if this was not possible.

An EvalContext can be provided, if none is givena default context is created which requires the nodes to havean attached environment.


Changed in version 2.4: the eval_ctx parameter was added.

canassign()

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

Subtract 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 listof keyword arguments (list of Keyword nodes), and dyn_args_and _dyn_kwargs has to be either None or a node that is used asnode 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 alist of Operands.

|Node type:
|——-
|Expr

class jinja2.nodes.Concat(nodes)

Concatenates the list of expressions provided after converting them tounicode.

|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 aName node, with a 'load' ctx and will return thecurrent Context object.

Here an example that assigns the current template name to avariable named foo:



  1. 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 forextensions 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 theattr() 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 ofthe 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 arefiltered. 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-onlybytestring 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 nodeaccess. For example ImportedName('cgi.escape') returns the escape_function from the cgi module on evaluation. Imports are optimized by thecompiler 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 nodesyourself but the parser provides afree_identifier() method that createsa new identifier for you. This identifier is not available from thetemplate 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 simpleconstants such as 42 or "foo" but it can be used to store morecomplex values such as lists too. Only constants with a saferepresentation (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 ofPair 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 argumentsfor subscripts. Like for Namectx specifies if the tupleis 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) butonly 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.NSRef(name, attr)

Reference to a namespace value assignment

|Node type:
|——-
|Expr

class jinja2.nodes.Slice(start, stop, step)

Represents a slice object. This must only be used as argument forSubscript.

|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, therest 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.AssignBlock(target, filter, body)

Assigns a block 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 withthe 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:



  1. 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 likeEvalContextModifier but will only modify theEvalContext 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 aName or Tuple), iter the iterable. body is a listof 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 notpass unsafe names to the name attribute. The compiler translates theattribute lookups directly into getattr calls and does not use thesubscript callback of the interface. As exported variables may notstart with double underscores (which the parser asserts) this is not aproblem for regular Jinja code, but if this node is used in an extensionextra care must be taken.

The list of names may contain tuples if aliases are wanted.

|Node type:
|——-
|Stmt

class jinja2.nodes.If(test, body, elif, _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 ofarguments and defaults a list of defaults if there are any. body isa 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.OverlayScope(context, body)

An overlay scope for extensions. This is a largely unoptimized scopethat however can be used to introduce completely arbitrary variables intoa sub scope from a dictionary or dictionary like object. The context_field has to evaluate to a dictionary object.

Example usage:



  1. OverlayScope(context=self.call_method('get_context'),
    body=[…])





New in version 2.10.


|Node type:
|——-
|Stmt

_class jinja2.nodes.Scope(body)

An artificial scope.

|Node type:
|——-
|Stmt

class jinja2.nodes.With(targets, values, body)

Specific node for with statements. In older versions of Jinja thewith statement was implemented on the base of the Scope node instead.


New in version 2.9.3.


|Node type:
|——-
|Stmt

class jinja2.nodes.Template(body)

Node that represents a template. This must be the outermost node thatis passed to the compiler.

|Node type:
|——-
|Node

exception jinja2.nodes.Impossible

Raised if the node could not perform a requested action.

原文:

http://jinja.pocoo.org/docs/2.10/extensions/