Skip to content
Myr

api.rst

This file

Path

docs/api.rst

877 lines · 30.2 KiB

Last changed by

Added docs for policiesArmin Ronacherbefore adoptione253520

History of this file

Take it

The walk stopped after 200 commits: lines older than 285c955 point at it.

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 1–14why, one step back
1API
2===34.. module:: jinja25 :synopsis: public Jinja2 API67This document describes the API to Jinja2 and not the template language. It8will be most useful as reference to those implementing the template interface9to the application and not those who are creating Jinja2 templates.1011Basics12------1314Jinja2 uses a central object called the template :class:`Environment`.

Merge pull request #293 from carldunham/docfixArmin Ronacherbefore adoption6a04a8b

line 15why, one step back
15Instances of this class are used to store the configuration and global objects,

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 16–21why, one step back
16and are used to load templates from the file system or other locations.
17Even if you are creating templates from strings by using the constructor of18:class:`Template` class, an environment is created automatically for you,19albeit a shared one.2021Most applications will create one :class:`Environment` object on application

Merge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption67d015e

line 22why, one step back
22initialization and use that to load templates. In some cases however, it's

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 23–46why, one step back
23useful to have multiple environments side by side, if different configurations
24are in use.2526The simplest way to configure Jinja2 to load templates for your application27looks roughly like this::2829 from jinja2 import Environment, PackageLoader30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))3132This will create a template environment with the default settings and a33loader that looks up the templates in the `templates` folder inside the34`yourapplication` python package. Different loaders are available35and you can also write your own if you want to load templates from a36database or other resources.3738To load a template from this environment you just have to call the39:meth:`get_template` method which then returns the loaded :class:`Template`::4041 template = env.get_template('mytemplate.html')4243To render it with some variables, just call the :meth:`render` method::4445 print template.render(the='variables', go='here')46

Merge branch 'merwok-patch-1'Markus Unterwaditzerbefore adoption45fe80e

line 47why, one step back
47Using a template loader rather than passing strings to :class:`Template`

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 48–156why, one step back
48or :meth:`Environment.from_string` has multiple advantages. Besides being
49a lot easier to use it also enables template inheritance.505152Unicode53-------5455Jinja2 is using Unicode internally which means that you have to pass Unicode56objects to the render function or bytestrings that only consist of ASCII57characters. Additionally newlines are normalized to one end of line58sequence which is per default UNIX style (``\n``).5960Python 2.x supports two ways of representing string objects. One is the61`str` type and the other is the `unicode` type, both of which extend a type62called `basestring`. Unfortunately the default is `str` which should not63be used to store text based information unless only ASCII characters are64used. With Python 2.6 it is possible to make `unicode` the default on a per65module level and with Python 3 it will be the default.6667To explicitly use a Unicode string you have to prefix the string literal68with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will69store the string as Unicode by decoding the string with the character70encoding from the current Python module. If no encoding is specified this71defaults to 'ASCII' which means that you can't use any non ASCII identifier.7273To set a better module encoding add the following comment to the first or74second line of the Python module using the Unicode literal::7576 # -*- coding: utf-8 -*-7778We recommend utf-8 as Encoding for Python modules and templates as it's79possible to represent every Unicode character in utf-8 and because it's80backwards compatible to ASCII. For Jinja2 the default encoding of templates81is assumed to be utf-8.8283It is not possible to use Jinja2 to process non-Unicode data. The reason84for this is that Jinja2 uses Unicode already on the language level. For85example Jinja2 treats the non-breaking space as valid whitespace inside86expressions which requires knowledge of the encoding or operating on an87Unicode string.8889For more details about Unicode in Python have a look at the excellent90`Unicode documentation`_.9192Another important thing is how Jinja2 is handling string literals in93templates. A naive implementation would be using Unicode strings for94all string literals but it turned out in the past that this is problematic95as some libraries are typechecking against `str` explicitly. For example96`datetime.strftime` does not accept Unicode arguments. To not break it97completely Jinja2 is returning `str` for strings that fit into ASCII and98for everything else `unicode`:99100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module101>>> m.a102'foo'103>>> m.b104u'f\xf6\xf6'105106107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html108109High Level API110--------------111112The high-level API is the API you will use in the application to load and113render Jinja2 templates. The :ref:`low-level-api` on the other side is only114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115<jinja-extensions>`.116117.. autoclass:: Environment([options])118 :members: from_string, get_template, select_template,119 get_or_select_template, join_path, extend, compile_expression,120 compile_templates, list_templates, add_extension121122 .. attribute:: shared123124 If a template was created by using the :class:`Template` constructor125 an environment is created automatically. These environments are126 created as shared environments which means that multiple templates127 may have the same anonymous environment. For all shared environments128 this attribute is `True`, else `False`.129130 .. attribute:: sandboxed131132 If the environment is sandboxed this attribute is `True`. For the133 sandbox mode have a look at the documentation for the134 :class:`~jinja2.sandbox.SandboxedEnvironment`.135136 .. attribute:: filters137138 A dict of filters for this environment. As long as no template was139 loaded it's safe to add new filters or remove old. For custom filters140 see :ref:`writing-filters`. For valid filter names have a look at141 :ref:`identifier-naming`.142143 .. attribute:: tests144145 A dict of test functions for this environment. As long as no146 template was loaded it's safe to modify this dict. For custom tests147 see :ref:`writing-tests`. For valid test names have a look at148 :ref:`identifier-naming`.149150 .. attribute:: globals151152 A dict of global variables. These variables are always available153 in a template. As long as no template was loaded it's safe154 to modify this dict. For more details see :ref:`global-namespace`.155 For valid object names have a look at :ref:`identifier-naming`.156

Added docs for policiesArmin Ronacherbefore adoptione253520

lines 157–162why, one step back
157 .. attribute:: policies
158159 A dictionary with :ref:`policies`. These can be reconfigured to160 change the runtime behavior or certain template features. Usually161 these are security related.162

Merge branch 'override-codegen-context'Markus Unterwaditzerbefore adoptionbd93bf3

lines 163–175why, one step back
163 .. attribute:: code_generator_class
164165 The class used for code generation. This should not be changed166 in most cases, unless you need to modify the Python code a167 template compiles to.168169 .. attribute:: context_class170171 The context used for templates. This should not be changed172 in most cases, unless you need to modify internals of how173 template variables are handled. For details, see174 :class:`~jinja2.runtime.Context`.175

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 176–188why, one step back
176 .. automethod:: overlay([options])
177178 .. method:: undefined([hint, obj, name, exc])179180 Creates a new :class:`Undefined` object for `name`. This is useful181 for filters or functions that may return undefined objects for182 some operations. All parameters except of `hint` should be provided183 as keyword parameters for better readability. The `hint` is used as184 error message for the exception if provided, otherwise the error185 message will be generated from `obj` and `name` automatically. The exception186 provided as `exc` is raised if something with the generated undefined187 object is done that the undefined object does not allow. The default188 exception is :exc:`UndefinedError`. If a `hint` is provided the

Merge pull request #437 from alexwlchan/masterMarkus Unterwaditzerbefore adoptiona0d47b9

line 189why, one step back
189 `name` may be omitted.

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 190–208why, one step back
190
191 The most common way to create an undefined object is by providing192 a name only::193194 return environment.undefined(name='some_name')195196 This means that the name `some_name` is not defined. If the name197 was from an attribute of an object it makes sense to tell the198 undefined object the holder object to improve the error message::199200 if not hasattr(obj, 'attr'):201 return environment.undefined(obj=obj, name='attr')202203 For a more complex example you can provide a hint. For example204 the :func:`first` filter creates an undefined object that way::205206 return environment.undefined('no first item, sequence was empty') 207208 If it the `name` or `obj` is known (for example because an attribute

Merge pull request #437 from alexwlchan/masterMarkus Unterwaditzerbefore adoptiona0d47b9

line 209why, one step back
209 was accessed) it should be passed to the undefined object, even if

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 210–237why, one step back
210 a custom `hint` is provided. This gives undefined objects the
211 possibility to enhance the error message.212213.. autoclass:: Template214 :members: module, make_module215216 .. attribute:: globals217218 The dict with the globals of that template. It's unsafe to modify219 this dict as it may be shared with other templates or the environment220 that loaded the template.221222 .. attribute:: name223224 The loading name of the template. If the template was loaded from a225 string this is `None`.226227 .. attribute:: filename228229 The filename of the template on the file system if it was loaded from230 there. Otherwise this is `None`.231232 .. automethod:: render([context])233234 .. automethod:: generate([context])235236 .. automethod:: stream([context])237

Started doc work for asyncArmin Ronacherbefore adoptiond8326d9

line 238why, one step back
238 .. automethod:: render_async([context])

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

line 239why, one step back
239

Started doc work for asyncArmin Ronacherbefore adoptiond8326d9

lines 240–242why, one step back
240 .. automethod:: generate_async([context])
241242

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 243–341why, one step back
243.. autoclass:: jinja2.environment.TemplateStream()
244 :members: disable_buffering, enable_buffering, dump245246247Autoescaping248------------249250.. versionadded:: 2.4251252As of Jinja 2.4 the preferred way to do autoescaping is to enable the253:ref:`autoescape-extension` and to configure a sensible default for254autoescaping. This makes it possible to enable and disable autoescaping255on a per-template basis (HTML versus text for instance).256257Here a recommended setup that enables autoescaping for templates ending258in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default259for all other extensions::260261 def guess_autoescape(template_name):262 if template_name is None or '.' not in template_name:263 return False264 ext = template_name.rsplit('.', 1)[1]265 return ext in ('html', 'htm', 'xml')266267 env = Environment(autoescape=guess_autoescape,268 loader=PackageLoader('mypackage'),269 extensions=['jinja2.ext.autoescape'])270271When implementing a guessing autoescape function, make sure you also272accept `None` as valid template name. This will be passed when generating273templates from strings.274275Inside the templates the behaviour can be temporarily changed by using276the `autoescape` block (see :ref:`autoescape-overrides`).277278279.. _identifier-naming:280281Notes on Identifiers282--------------------283284Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to285match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters286are currently not allowed. This limitation will probably go away as soon as287unicode identifiers are fully specified for Python 3.288289Filters and tests are looked up in separate namespaces and have slightly290modified identifier syntax. Filters and tests may contain dots to group291filters and tests by topic. For example it's perfectly valid to add a292function into the filter dict and call it `to.unicode`. The regular293expression for filter and test identifiers is294``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.295296297Undefined Types298---------------299300These classes can be used as undefined types. The :class:`Environment`301constructor takes an `undefined` parameter that can be one of those classes302or a custom subclass of :class:`Undefined`. Whenever the template engine is303unable to look up a name or access an attribute one of those objects is304created and returned. Some operations on undefined values are then allowed,305others fail.306307The closest to regular Python behavior is the `StrictUndefined` which308disallows all operations beside testing if it's an undefined object.309310.. autoclass:: jinja2.Undefined()311312 .. attribute:: _undefined_hint313314 Either `None` or an unicode string with the error message for315 the undefined object.316317 .. attribute:: _undefined_obj318319 Either `None` or the owner object that caused the undefined object320 to be created (for example because an attribute does not exist).321322 .. attribute:: _undefined_name323324 The name for the undefined variable / attribute or just `None`325 if no such information exists.326327 .. attribute:: _undefined_exception328329 The exception that the undefined object wants to raise. This330 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.331332 .. method:: _fail_with_undefined_error(\*args, \**kwargs)333334 When called with any arguments this method raises335 :attr:`_undefined_exception` with an error message generated336 from the undefined hints stored on the undefined object.337338.. autoclass:: jinja2.DebugUndefined()339340.. autoclass:: jinja2.StrictUndefined()341

Added tests for logging undefined and added it to the docs.Armin Ronacherbefore adoption6e9dfbf

lines 342–346why, one step back
342There is also a factory function that can decorate undefined objects to
343implement logging on failures:344345.. autofunction:: jinja2.make_logging_undefined346

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 347–480why, one step back
347Undefined objects are created by calling :attr:`undefined`.
348349.. admonition:: Implementation350351 :class:`Undefined` objects are implemented by overriding the special352 `__underscore__` methods. For example the default :class:`Undefined`353 class implements `__unicode__` in a way that it returns an empty354 string, however `__int__` and others still fail with an exception. To355 allow conversion to int by returning ``0`` you can implement your own::356357 class NullUndefined(Undefined):358 def __int__(self):359 return 0360 def __float__(self):361 return 0.0362363 To disallow a method, just override it and raise364 :attr:`~Undefined._undefined_exception`. Because this is a very common365 idom in undefined objects there is the helper method366 :meth:`~Undefined._fail_with_undefined_error` that does the error raising367 automatically. Here a class that works like the regular :class:`Undefined`368 but chokes on iteration::369370 class NonIterableUndefined(Undefined):371 __iter__ = Undefined._fail_with_undefined_error372373374The Context375-----------376377.. autoclass:: jinja2.runtime.Context()378 :members: resolve, get_exported, get_all379380 .. attribute:: parent381382 A dict of read only, global variables the template looks up. These383 can either come from another :class:`Context`, from the384 :attr:`Environment.globals` or :attr:`Template.globals` or points385 to a dict created by combining the globals with the variables386 passed to the render function. It must not be altered.387388 .. attribute:: vars389390 The template local variables. This list contains environment and391 context functions from the :attr:`parent` scope as well as local392 modifications and exported variables from the template. The template393 will modify this dict during template evaluation but filters and394 context functions are not allowed to modify it.395396 .. attribute:: environment397398 The environment that loaded the template.399400 .. attribute:: exported_vars401402 This set contains all the names the template exports. The values for403 the names are in the :attr:`vars` dict. In order to get a copy of the404 exported variables as dict, :meth:`get_exported` can be used.405406 .. attribute:: name407408 The load name of the template owning this context.409410 .. attribute:: blocks411412 A dict with the current mapping of blocks in the template. The keys413 in this dict are the names of the blocks, and the values a list of414 blocks registered. The last item in each list is the current active415 block (latest in the inheritance chain).416417 .. attribute:: eval_ctx418419 The current :ref:`eval-context`.420421 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)422423424.. admonition:: Implementation425426 Context is immutable for the same reason Python's frame locals are427 immutable inside functions. Both Jinja2 and Python are not using the428 context / frame locals as data storage for variables but only as primary429 data source.430431 When a template accesses a variable the template does not define, Jinja2432 looks up the variable in the context, after that the variable is treated433 as if it was defined in the template.434435436.. _loaders:437438Loaders439-------440441Loaders are responsible for loading templates from a resource such as the442file system. The environment will keep the compiled modules in memory like443Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in444size by default and templates are automatically reloaded.445All loaders are subclasses of :class:`BaseLoader`. If you want to create your446own loader, subclass :class:`BaseLoader` and override `get_source`.447448.. autoclass:: jinja2.BaseLoader449 :members: get_source, load450451Here a list of the builtin loaders Jinja2 provides:452453.. autoclass:: jinja2.FileSystemLoader454455.. autoclass:: jinja2.PackageLoader456457.. autoclass:: jinja2.DictLoader458459.. autoclass:: jinja2.FunctionLoader460461.. autoclass:: jinja2.PrefixLoader462463.. autoclass:: jinja2.ChoiceLoader464465.. autoclass:: jinja2.ModuleLoader466467468.. _bytecode-cache:469470Bytecode Cache471--------------472473Jinja 2.1 and higher support external bytecode caching. Bytecode caches make474it possible to store the generated bytecode on the file system or a different475location to avoid parsing the templates on first use.476477This is especially useful if you have a web application that is initialized on478the first request and Jinja compiles many templates at once which slows down479the application.480

Merge pull request #230 from p1otr/masterArmin Ronacherbefore adoptionc97fa10

line 481why, one step back
481To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 482–507why, one step back
482
483.. autoclass:: jinja2.BytecodeCache484 :members: load_bytecode, dump_bytecode, clear485486.. autoclass:: jinja2.bccache.Bucket487 :members: write_bytecode, load_bytecode, bytecode_from_string,488 bytecode_to_string, reset489490 .. attribute:: environment491492 The :class:`Environment` that created the bucket.493494 .. attribute:: key495496 The unique cache key for this bucket497498 .. attribute:: code499500 The bytecode if it's loaded, otherwise `None`.501502503Builtin bytecode caches:504505.. autoclass:: jinja2.FileSystemBytecodeCache506507.. autoclass:: jinja2.MemcachedBytecodeCache

Started doc work for asyncArmin Ronacherbefore adoptiond8326d9

lines 508–543why, one step back
508
509510Async Support511-------------512513Starting with version 2.9, Jinja2 also supports the Python `async` and514`await` constructs. As far as template designers go this feature is515entirely opaque to them however as a developer you should be aware of how516it's implemented as it influences what type of APIs you can safely expose517to the template environment.518519First you need to be aware that by default async support is disabled as520enabling it will generate different template code behind the scenes which521passes everything through the asyncio event loop. This is important to522understand because it has some impact to what you are doing:523524* template rendering will require an event loop to be set for the525 current thread (``asyncio.get_event_loop`` needs to return one)526* all template generation code internally runs async generators which527 means that you will pay a performance penalty even if the non sync528 methods are used!529* The sync methods are based on async methods if the async mode is530 enabled which means that `render` for instance will internally invoke531 `render_async` and run it as part of the current event loop until the532 execution finished.533534Awaitable objects can be returned from functions in templates and any535function call in a template will automatically await the result. This536means that you can let provide a method that asynchronously loads data537from a database if you so desire and from the template designer's point of538view this is just another function they can call. This means that the539``await`` you would normally issue in Python is implied. However this540only applies to function calls. If an attribute for instance would be an541avaitable object then this would not result in the expected behavior.542543Likewise iterations with a `for` loop support async iterators.

Added docs for policiesArmin Ronacherbefore adoptione253520

lines 544–566why, one step back
544
545.. _policies:546547Policies548--------549550Starting with Jinja 2.9 policies can be configured on the environment551which can slightly influence how filters and other template constructs552behave. They can be configured with the553:attr:`~jinja2.Environment.policies` attribute.554555Example::556557 env.policies['urlize.rel'] = 'nofollow noopener'558559``urlize.rel``:560 A string that defines the items for the `rel` attribute of generated561 links with the `urlize` filter. These items are always added. The562 default is `noopener`.563564``urlize.target``:565 The default target that is issued for links from the `urlize` filter566 if no other target is defined by the call explicitly.

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 567–652why, one step back
567
568569Utilities570---------571572These helper functions and classes are useful if you add custom filters or573functions to a Jinja2 environment.574575.. autofunction:: jinja2.environmentfilter576577.. autofunction:: jinja2.contextfilter578579.. autofunction:: jinja2.evalcontextfilter580581.. autofunction:: jinja2.environmentfunction582583.. autofunction:: jinja2.contextfunction584585.. autofunction:: jinja2.evalcontextfunction586587.. function:: escape(s)588589 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`590 to HTML-safe sequences. Use this if you need to display text that might591 contain such characters in HTML. This function will not escaped objects592 that do have an HTML representation such as already escaped data.593594 The return value is a :class:`Markup` string.595596.. autofunction:: jinja2.clear_caches597598.. autofunction:: jinja2.is_undefined599600.. autoclass:: jinja2.Markup([string])601 :members: escape, unescape, striptags602603.. admonition:: Note604605 The Jinja2 :class:`Markup` class is compatible with at least Pylons and606 Genshi. It's expected that more template engines and framework will pick607 up the `__html__` concept soon.608609610Exceptions611----------612613.. autoexception:: jinja2.TemplateError614615.. autoexception:: jinja2.UndefinedError616617.. autoexception:: jinja2.TemplateNotFound618619.. autoexception:: jinja2.TemplatesNotFound620621.. autoexception:: jinja2.TemplateSyntaxError622623 .. attribute:: message624625 The error message as utf-8 bytestring.626627 .. attribute:: lineno628629 The line number where the error occurred630631 .. attribute:: name632633 The load name for the template as unicode string.634635 .. attribute:: filename636637 The filename that loaded the template as bytestring in the encoding638 of the file system (most likely utf-8 or mbcs on Windows systems).639640 The reason why the filename and error message are bytestrings and not641 unicode strings is that Python 2.x is not using unicode for exceptions642 and tracebacks as well as the compiler. This will change with Python 3.643644.. autoexception:: jinja2.TemplateAssertionError645646647.. _writing-filters:648649Custom Filters650--------------651652Custom filters are just regular Python functions that take the left side of

Merge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption67d015e

line 653why, one step back
653the filter as first argument and the arguments passed to the filter as

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 654–691why, one step back
654extra arguments or keyword arguments.
655656For example in the filter ``{{ 42|myfilter(23) }}`` the function would be657called with ``myfilter(42, 23)``. Here for example a simple filter that can658be applied to datetime objects to format them::659660 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):661 return value.strftime(format)662663You can register it on the template environment by updating the664:attr:`~Environment.filters` dict on the environment::665666 environment.filters['datetimeformat'] = datetimeformat667668Inside the template it can then be used as follows:669670.. sourcecode:: jinja671672 written on: {{ article.pub_date|datetimeformat }}673 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}674675Filters can also be passed the current template context or environment. This676is useful if a filter wants to return an undefined value or check the current677:attr:`~Environment.autoescape` setting. For this purpose three decorators678exist: :func:`environmentfilter`, :func:`contextfilter` and679:func:`evalcontextfilter`.680681Here a small example filter that breaks a text into HTML line breaks and682paragraphs and marks the return value as safe HTML string if autoescaping is683enabled::684685 import re686 from jinja2 import evalcontextfilter, Markup, escape687688 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')689690 @evalcontextfilter691 def nl2br(eval_ctx, value):

Merge pull request #343 from joernhees/patch-1Markus Unterwaditzerbefore adoption376a7a5

line 692why, one step back
692 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 693–707why, one step back
693 for p in _paragraph_re.split(escape(value)))
694 if eval_ctx.autoescape:695 result = Markup(result)696 return result697698Context filters work the same just that the first argument is the current699active :class:`Context` rather then the environment.700701702.. _eval-context:703704Evaluation Context705------------------706707The evaluation context (short eval context or eval ctx) is a new object

Merge pull request #230 from p1otr/masterArmin Ronacherbefore adoptionc97fa10

line 708why, one step back
708introduced in Jinja 2.4 that makes it possible to activate and deactivate

Added an explanation for how with_metaclass worksArmin Ronacherbefore adoption285c955

lines 709–877why, one step back
709compiled features at runtime.
710711Currently it is only used to enable and disable the automatic escaping but712can be used for extensions as well.713714In previous Jinja versions filters and functions were marked as715environment callables in order to check for the autoescape status from the716environment. In new versions it's encouraged to check the setting from the717evaluation context instead.718719Previous versions::720721 @environmentfilter722 def filter(env, value):723 result = do_something(value)724 if env.autoescape:725 result = Markup(result)726 return result727728In new versions you can either use a :func:`contextfilter` and access the729evaluation context from the actual context, or use a730:func:`evalcontextfilter` which directly passes the evaluation context to731the function::732733 @contextfilter734 def filter(context, value):735 result = do_something(value)736 if context.eval_ctx.autoescape:737 result = Markup(result)738 return result739740 @evalcontextfilter741 def filter(eval_ctx, value):742 result = do_something(value)743 if eval_ctx.autoescape:744 result = Markup(result)745 return result746747The evaluation context must not be modified at runtime. Modifications748must only happen with a :class:`nodes.EvalContextModifier` and749:class:`nodes.ScopedEvalContextModifier` from an extension, not on the750eval context object itself.751752.. autoclass:: jinja2.nodes.EvalContext753754 .. attribute:: autoescape755756 `True` or `False` depending on if autoescaping is active or not.757758 .. attribute:: volatile759760 `True` if the compiler cannot evaluate some expressions at compile761 time. At runtime this should always be `False`.762763764.. _writing-tests:765766Custom Tests767------------768769Tests work like filters just that there is no way for a test to get access770to the environment or context and that they can't be chained. The return771value of a test should be `True` or `False`. The purpose of a test is to772give the template designers the possibility to perform type and conformability773checks.774775Here a simple test that checks if a variable is a prime number::776777 import math778779 def is_prime(n):780 if n == 2:781 return True782 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):783 if n % i == 0:784 return False785 return True786 787788You can register it on the template environment by updating the789:attr:`~Environment.tests` dict on the environment::790791 environment.tests['prime'] = is_prime792793A template designer can then use the test like this:794795.. sourcecode:: jinja796797 {% if 42 is prime %}798 42 is a prime number799 {% else %}800 42 is not a prime number801 {% endif %}802803804.. _global-namespace:805806The Global Namespace807--------------------808809Variables stored in the :attr:`Environment.globals` dict are special as they810are available for imported templates too, even if they are imported without811context. This is the place where you can put variables and functions812that should be available all the time. Additionally :attr:`Template.globals`813exist that are variables available to a specific template that are available814to all :meth:`~Template.render` calls.815816817.. _low-level-api:818819Low Level API820-------------821822The low level API exposes functionality that can be useful to understand some823implementation details, debugging purposes or advanced :ref:`extension824<jinja-extensions>` techniques. Unless you know exactly what you are doing we825don't recommend using any of those.826827.. automethod:: Environment.lex828829.. automethod:: Environment.parse830831.. automethod:: Environment.preprocess832833.. automethod:: Template.new_context834835.. method:: Template.root_render_func(context)836837 This is the low level render function. It's passed a :class:`Context`838 that has to be created by :meth:`new_context` of the same template or839 a compatible template. This render function is generated by the840 compiler from the template code and returns a generator that yields841 unicode strings.842843 If an exception in the template code happens the template engine will844 not rewrite the exception but pass through the original one. As a845 matter of fact this function should only be called from within a846 :meth:`render` / :meth:`generate` / :meth:`stream` call.847848.. attribute:: Template.blocks849850 A dict of block render functions. Each of these functions works exactly851 like the :meth:`root_render_func` with the same limitations.852853.. attribute:: Template.is_up_to_date854855 This attribute is `False` if there is a newer version of the template856 available, otherwise `True`.857858.. admonition:: Note859860 The low-level API is fragile. Future Jinja2 versions will try not to861 change it in a backwards incompatible way but modifications in the Jinja2862 core may shine through. For example if Jinja2 introduces a new AST node863 in later versions that may be returned by :meth:`~Environment.parse`.864865The Meta API866------------867868.. versionadded:: 2.2869870The meta API returns some information about abstract syntax trees that871could help applications to implement more advanced template concepts. All872the functions of the meta API operate on an abstract syntax tree as873returned by the :meth:`Environment.parse` method.874875.. autofunction:: jinja2.meta.find_undeclared_variables876877.. autofunction:: jinja2.meta.find_referenced_templates