Skip to content
Myr

api.rst

This file

Path

docs/api.rst

935 lines · 32.2 KiB

Last changed by

Merge pull request #1161 from ldealmei/patch-1David Lordbefore adoptioneccf9a0

History of this file

Take it

1API2===34.. module:: jinja25    :noindex:6    :synopsis: public Jinja API78This document describes the API to Jinja and not the template language9(for that, see :doc:`/templates`). It will be most useful as reference10to those implementing the template interface to the application and not11those who are creating Jinja templates.1213Basics14------1516Jinja uses a central object called the template :class:`Environment`.17Instances of this class are used to store the configuration and global objects,18and are used to load templates from the file system or other locations.19Even if you are creating templates from strings by using the constructor of20:class:`Template` class, an environment is created automatically for you,21albeit a shared one.2223Most applications will create one :class:`Environment` object on application24initialization and use that to load templates.  In some cases however, it's25useful to have multiple environments side by side, if different configurations26are in use.2728The simplest way to configure Jinja to load templates for your application29looks roughly like this::3031    from jinja2 import Environment, PackageLoader, select_autoescape32    env = Environment(33        loader=PackageLoader('yourapplication', 'templates'),34        autoescape=select_autoescape(['html', 'xml'])35    )3637This will create a template environment with the default settings and a38loader that looks up the templates in the `templates` folder inside the39`yourapplication` python package.  Different loaders are available40and you can also write your own if you want to load templates from a41database or other resources.  This also enables autoescaping for HTML and42XML files.4344To load a template from this environment you just have to call the45:meth:`get_template` method which then returns the loaded :class:`Template`::4647    template = env.get_template('mytemplate.html')4849To render it with some variables, just call the :meth:`render` method::5051    print(template.render(the='variables', go='here'))5253Using a template loader rather than passing strings to :class:`Template`54or :meth:`Environment.from_string` has multiple advantages.  Besides being55a lot easier to use it also enables template inheritance.5657.. admonition:: Notes on Autoescaping5859   In future versions of Jinja we might enable autoescaping by default60   for security reasons.  As such you are encouraged to explicitly61   configure autoescaping now instead of relying on the default.626364Unicode65-------6667Jinja is using Unicode internally which means that you have to pass Unicode68objects to the render function or bytestrings that only consist of ASCII69characters.  Additionally newlines are normalized to one end of line70sequence which is per default UNIX style (``\n``).7172Python 2.x supports two ways of representing string objects.  One is the73`str` type and the other is the `unicode` type, both of which extend a type74called `basestring`.  Unfortunately the default is `str` which should not75be used to store text based information unless only ASCII characters are76used.  With Python 2.6 it is possible to make `unicode` the default on a per77module level and with Python 3 it will be the default.7879To explicitly use a Unicode string you have to prefix the string literal80with a `u`: ``u'Hänsel und Gretel sagen Hallo'``.  That way Python will81store the string as Unicode by decoding the string with the character82encoding from the current Python module.  If no encoding is specified this83defaults to 'ASCII' which means that you can't use any non ASCII identifier.8485To set a better module encoding add the following comment to the first or86second line of the Python module using the Unicode literal::8788    # -*- coding: utf-8 -*-8990We recommend utf-8 as Encoding for Python modules and templates as it's91possible to represent every Unicode character in utf-8 and because it's92backwards compatible to ASCII.  For Jinja the default encoding of templates93is assumed to be utf-8.9495It is not possible to use Jinja to process non-Unicode data.  The reason96for this is that Jinja uses Unicode already on the language level.  For97example Jinja treats the non-breaking space as valid whitespace inside98expressions which requires knowledge of the encoding or operating on an99Unicode string.100101For more details about Unicode in Python have a look at the excellent102`Unicode documentation`_.103104Another important thing is how Jinja is handling string literals in105templates.  A naive implementation would be using Unicode strings for106all string literals but it turned out in the past that this is problematic107as some libraries are typechecking against `str` explicitly.  For example108`datetime.strftime` does not accept Unicode arguments.  To not break it109completely Jinja is returning `str` for strings that fit into ASCII and110for everything else `unicode`:111112>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module113>>> m.a114'foo'115>>> m.b116u'f\xf6\xf6'117118119.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html120121High Level API122--------------123124The high-level API is the API you will use in the application to load and125render Jinja templates.  The :ref:`low-level-api` on the other side is only126useful if you want to dig deeper into Jinja or :ref:`develop extensions127<jinja-extensions>`.128129.. autoclass:: Environment([options])130    :members: from_string, get_template, select_template,131              get_or_select_template, join_path, extend, compile_expression,132              compile_templates, list_templates, add_extension133134    .. attribute:: shared135136        If a template was created by using the :class:`Template` constructor137        an environment is created automatically.  These environments are138        created as shared environments which means that multiple templates139        may have the same anonymous environment.  For all shared environments140        this attribute is `True`, else `False`.141142    .. attribute:: sandboxed143144        If the environment is sandboxed this attribute is `True`.  For the145        sandbox mode have a look at the documentation for the146        :class:`~jinja2.sandbox.SandboxedEnvironment`.147148    .. attribute:: filters149150        A dict of filters for this environment.  As long as no template was151        loaded it's safe to add new filters or remove old.  For custom filters152        see :ref:`writing-filters`.  For valid filter names have a look at153        :ref:`identifier-naming`.154155    .. attribute:: tests156157        A dict of test functions for this environment.  As long as no158        template was loaded it's safe to modify this dict.  For custom tests159        see :ref:`writing-tests`.  For valid test names have a look at160        :ref:`identifier-naming`.161162    .. attribute:: globals163164        A dict of global variables.  These variables are always available165        in a template.  As long as no template was loaded it's safe166        to modify this dict.  For more details see :ref:`global-namespace`.167        For valid object names have a look at :ref:`identifier-naming`.168169    .. attribute:: policies170171        A dictionary with :ref:`policies`.  These can be reconfigured to172        change the runtime behavior or certain template features.  Usually173        these are security related.174175    .. attribute:: code_generator_class176177       The class used for code generation.  This should not be changed178       in most cases, unless you need to modify the Python code a179       template compiles to.180181    .. attribute:: context_class182183       The context used for templates.  This should not be changed184       in most cases, unless you need to modify internals of how185       template variables are handled.  For details, see186       :class:`~jinja2.runtime.Context`.187188    .. automethod:: overlay([options])189190    .. method:: undefined([hint, obj, name, exc])191192        Creates a new :class:`Undefined` object for `name`.  This is useful193        for filters or functions that may return undefined objects for194        some operations.  All parameters except of `hint` should be provided195        as keyword parameters for better readability.  The `hint` is used as196        error message for the exception if provided, otherwise the error197        message will be generated from `obj` and `name` automatically.  The exception198        provided as `exc` is raised if something with the generated undefined199        object is done that the undefined object does not allow.  The default200        exception is :exc:`UndefinedError`.  If a `hint` is provided the201        `name` may be omitted.202203        The most common way to create an undefined object is by providing204        a name only::205206            return environment.undefined(name='some_name')207208        This means that the name `some_name` is not defined.  If the name209        was from an attribute of an object it makes sense to tell the210        undefined object the holder object to improve the error message::211212            if not hasattr(obj, 'attr'):213                return environment.undefined(obj=obj, name='attr')214215        For a more complex example you can provide a hint.  For example216        the :func:`first` filter creates an undefined object that way::217218            return environment.undefined('no first item, sequence was empty')219220        If it the `name` or `obj` is known (for example because an attribute221        was accessed) it should be passed to the undefined object, even if222        a custom `hint` is provided.  This gives undefined objects the223        possibility to enhance the error message.224225.. autoclass:: Template226    :members: module, make_module227228    .. attribute:: globals229230        The dict with the globals of that template.  It's unsafe to modify231        this dict as it may be shared with other templates or the environment232        that loaded the template.233234    .. attribute:: name235236        The loading name of the template.  If the template was loaded from a237        string this is `None`.238239    .. attribute:: filename240241        The filename of the template on the file system if it was loaded from242        there.  Otherwise this is `None`.243244    .. automethod:: render([context])245246    .. automethod:: generate([context])247248    .. automethod:: stream([context])249250    .. automethod:: render_async([context])251252    .. automethod:: generate_async([context])253254255.. autoclass:: jinja2.environment.TemplateStream()256    :members: disable_buffering, enable_buffering, dump257258259Autoescaping260------------261262.. versionchanged:: 2.4263264Jinja now comes with autoescaping support.  As of Jinja 2.9 the265autoescape extension is removed and built-in.  However autoescaping is266not yet enabled by default though this will most likely change in the267future.  It's recommended to configure a sensible default for268autoescaping.  This makes it possible to enable and disable autoescaping269on a per-template basis (HTML versus text for instance).270271.. autofunction:: jinja2.select_autoescape272273Here a recommended setup that enables autoescaping for templates ending274in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default275for all other extensions.  You can use the :func:`~jinja2.select_autoescape`276function for this::277278    from jinja2 import Environment, select_autoescape279    env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),280                      loader=PackageLoader('mypackage'))281282The :func:`~jinja.select_autoescape` function returns a function that283works roughly like this::284285    def autoescape(template_name):286        if template_name is None:287            return False288        if template_name.endswith(('.html', '.htm', '.xml'))289290When implementing a guessing autoescape function, make sure you also291accept `None` as valid template name.  This will be passed when generating292templates from strings.  You should always configure autoescaping as293defaults in the future might change.294295Inside the templates the behaviour can be temporarily changed by using296the `autoescape` block (see :ref:`autoescape-overrides`).297298299.. _identifier-naming:300301Notes on Identifiers302--------------------303304Jinja uses Python naming rules. Valid identifiers can be any combination305of Unicode characters accepted by Python.306307Filters and tests are looked up in separate namespaces and have slightly308modified identifier syntax.  Filters and tests may contain dots to group309filters and tests by topic.  For example it's perfectly valid to add a310function into the filter dict and call it `to.unicode`.  The regular311expression for filter and test identifiers is312``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.313314315Undefined Types316---------------317318These classes can be used as undefined types.  The :class:`Environment`319constructor takes an `undefined` parameter that can be one of those classes320or a custom subclass of :class:`Undefined`.  Whenever the template engine is321unable to look up a name or access an attribute one of those objects is322created and returned.  Some operations on undefined values are then allowed,323others fail.324325The closest to regular Python behavior is the :class:`StrictUndefined` which326disallows all operations beside testing if it's an undefined object.327328.. autoclass:: jinja2.Undefined()329330    .. attribute:: _undefined_hint331332        Either `None` or an unicode string with the error message for333        the undefined object.334335    .. attribute:: _undefined_obj336337        Either `None` or the owner object that caused the undefined object338        to be created (for example because an attribute does not exist).339340    .. attribute:: _undefined_name341342        The name for the undefined variable / attribute or just `None`343        if no such information exists.344345    .. attribute:: _undefined_exception346347        The exception that the undefined object wants to raise.  This348        is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.349350    .. method:: _fail_with_undefined_error(\*args, \**kwargs)351352        When called with any arguments this method raises353        :attr:`_undefined_exception` with an error message generated354        from the undefined hints stored on the undefined object.355356.. autoclass:: jinja2.ChainableUndefined()357358.. autoclass:: jinja2.DebugUndefined()359360.. autoclass:: jinja2.StrictUndefined()361362There is also a factory function that can decorate undefined objects to363implement logging on failures:364365.. autofunction:: jinja2.make_logging_undefined366367Undefined objects are created by calling :attr:`undefined`.368369.. admonition:: Implementation370371    :class:`Undefined` objects are implemented by overriding the special372    `__underscore__` methods.  For example the default :class:`Undefined`373    class implements `__unicode__` in a way that it returns an empty374    string, however `__int__` and others still fail with an exception.  To375    allow conversion to int by returning ``0`` you can implement your own::376377        class NullUndefined(Undefined):378            def __int__(self):379                return 0380            def __float__(self):381                return 0.0382383    To disallow a method, just override it and raise384    :attr:`~Undefined._undefined_exception`.  Because this is a very common385    idiom in undefined objects there is the helper method386    :meth:`~Undefined._fail_with_undefined_error` that does the error raising387    automatically.  Here a class that works like the regular :class:`Undefined`388    but chokes on iteration::389390        class NonIterableUndefined(Undefined):391            __iter__ = Undefined._fail_with_undefined_error392393394The Context395-----------396397.. autoclass:: jinja2.runtime.Context()398    :members: resolve, get_exported, get_all399400    .. attribute:: parent401402        A dict of read only, global variables the template looks up.  These403        can either come from another :class:`Context`, from the404        :attr:`Environment.globals` or :attr:`Template.globals` or points405        to a dict created by combining the globals with the variables406        passed to the render function.  It must not be altered.407408    .. attribute:: vars409410        The template local variables.  This list contains environment and411        context functions from the :attr:`parent` scope as well as local412        modifications and exported variables from the template.  The template413        will modify this dict during template evaluation but filters and414        context functions are not allowed to modify it.415416    .. attribute:: environment417418        The environment that loaded the template.419420    .. attribute:: exported_vars421422        This set contains all the names the template exports.  The values for423        the names are in the :attr:`vars` dict.  In order to get a copy of the424        exported variables as dict, :meth:`get_exported` can be used.425426    .. attribute:: name427428        The load name of the template owning this context.429430    .. attribute:: blocks431432        A dict with the current mapping of blocks in the template.  The keys433        in this dict are the names of the blocks, and the values a list of434        blocks registered.  The last item in each list is the current active435        block (latest in the inheritance chain).436437    .. attribute:: eval_ctx438439        The current :ref:`eval-context`.440441    .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)442443444.. admonition:: Implementation445446    Context is immutable for the same reason Python's frame locals are447    immutable inside functions.  Both Jinja and Python are not using the448    context / frame locals as data storage for variables but only as primary449    data source.450451    When a template accesses a variable the template does not define, Jinja452    looks up the variable in the context, after that the variable is treated453    as if it was defined in the template.454455456.. _loaders:457458Loaders459-------460461Loaders are responsible for loading templates from a resource such as the462file system.  The environment will keep the compiled modules in memory like463Python's `sys.modules`.  Unlike `sys.modules` however this cache is limited in464size by default and templates are automatically reloaded.465All loaders are subclasses of :class:`BaseLoader`.  If you want to create your466own loader, subclass :class:`BaseLoader` and override `get_source`.467468.. autoclass:: jinja2.BaseLoader469    :members: get_source, load470471Here a list of the builtin loaders Jinja provides:472473.. autoclass:: jinja2.FileSystemLoader474475.. autoclass:: jinja2.PackageLoader476477.. autoclass:: jinja2.DictLoader478479.. autoclass:: jinja2.FunctionLoader480481.. autoclass:: jinja2.PrefixLoader482483.. autoclass:: jinja2.ChoiceLoader484485.. autoclass:: jinja2.ModuleLoader486487488.. _bytecode-cache:489490Bytecode Cache491--------------492493Jinja 2.1 and higher support external bytecode caching.  Bytecode caches make494it possible to store the generated bytecode on the file system or a different495location to avoid parsing the templates on first use.496497This is especially useful if you have a web application that is initialized on498the first request and Jinja compiles many templates at once which slows down499the application.500501To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.502503.. autoclass:: jinja2.BytecodeCache504    :members: load_bytecode, dump_bytecode, clear505506.. autoclass:: jinja2.bccache.Bucket507    :members: write_bytecode, load_bytecode, bytecode_from_string,508              bytecode_to_string, reset509510    .. attribute:: environment511512        The :class:`Environment` that created the bucket.513514    .. attribute:: key515516        The unique cache key for this bucket517518    .. attribute:: code519520        The bytecode if it's loaded, otherwise `None`.521522523Builtin bytecode caches:524525.. autoclass:: jinja2.FileSystemBytecodeCache526527.. autoclass:: jinja2.MemcachedBytecodeCache528529530Async Support531-------------532533.. versionadded:: 2.9534535Jinja supports the Python ``async`` and ``await`` syntax. For the536template designer, this support (when enabled) is entirely transparent,537templates continue to look exactly the same. However, developers should538be aware of the implementation as it affects what types of APIs you can539use.540541By default, async support is disabled. Enabling it will cause the542environment to compile different code behind the scenes in order to543handle async and sync code in an asyncio event loop. This has the544following implications:545546-   Template rendering requires an event loop to be available to the547    current thread. :func:`asyncio.get_event_loop` must return an event548    loop.549-   The compiled code uses ``await`` for functions and attributes, and550    uses ``async for`` loops. In order to support using both async and551    sync functions in this context, a small wrapper is placed around552    all calls and access, which add overhead compared to purely async553    code.554-   Sync methods and filters become wrappers around their corresponding555    async implementations where needed. For example, ``render`` invokes556    ``async_render``, and ``|map`` supports async iterables.557558Awaitable objects can be returned from functions in templates and any559function call in a template will automatically await the result. The560``await`` you would normally add in Python is implied. For example, you561can provide a method that asynchronously loads data from a database, and562from the template designer's point of view it can be called like any563other function.564565566.. _policies:567568Policies569--------570571Starting with Jinja 2.9 policies can be configured on the environment572which can slightly influence how filters and other template constructs573behave.  They can be configured with the574:attr:`~jinja2.Environment.policies` attribute.575576Example::577578    env.policies['urlize.rel'] = 'nofollow noopener'579580``compiler.ascii_str``:581    This boolean controls on Python 2 if Jinja should store ASCII only582    literals as bytestring instead of unicode strings.  This used to be583    always enabled for Jinja versions below 2.9 and now can be changed.584    Traditionally it was done this way since some APIs in Python 2 failed585    badly for unicode strings (for instance the datetime strftime API).586    Now however sometimes the inverse is true (for instance str.format).587    If this is set to False then all strings are stored as unicode588    internally.589590``truncate.leeway``:591    Configures the leeway default for the `truncate` filter.  Leeway as592    introduced in 2.9 but to restore compatibility with older templates593    it can be configured to `0` to get the old behavior back.  The default594    is `5`.595596``urlize.rel``:597    A string that defines the items for the `rel` attribute of generated598    links with the `urlize` filter.  These items are always added.  The599    default is `noopener`.600601``urlize.target``:602    The default target that is issued for links from the `urlize` filter603    if no other target is defined by the call explicitly.604605``json.dumps_function``:606    If this is set to a value other than `None` then the `tojson` filter607    will dump with this function instead of the default one.  Note that608    this function should accept arbitrary extra arguments which might be609    passed in the future from the filter.  Currently the only argument610    that might be passed is `indent`.  The default dump function is611    ``json.dumps``.612613``json.dumps_kwargs``:614    Keyword arguments to be passed to the dump function.  The default is615    ``{'sort_keys': True}``.616617.. _ext-i18n-trimmed:618619``ext.i18n.trimmed``:620    If this is set to `True`, ``{% trans %}`` blocks of the621    :ref:`i18n-extension` will always unify linebreaks and surrounding622    whitespace as if the `trimmed` modifier was used.623624625Utilities626---------627628These helper functions and classes are useful if you add custom filters or629functions to a Jinja environment.630631.. autofunction:: jinja2.environmentfilter632633.. autofunction:: jinja2.contextfilter634635.. autofunction:: jinja2.evalcontextfilter636637.. autofunction:: jinja2.environmentfunction638639.. autofunction:: jinja2.contextfunction640641.. autofunction:: jinja2.evalcontextfunction642643.. function:: escape(s)644645    Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`646    to HTML-safe sequences.  Use this if you need to display text that might647    contain such characters in HTML.  This function will not escaped objects648    that do have an HTML representation such as already escaped data.649650    The return value is a :class:`Markup` string.651652.. autofunction:: jinja2.clear_caches653654.. autofunction:: jinja2.is_undefined655656.. autoclass:: jinja2.Markup([string])657    :members: escape, unescape, striptags658659.. admonition:: Note660661    The Jinja :class:`Markup` class is compatible with at least Pylons and662    Genshi.  It's expected that more template engines and framework will pick663    up the `__html__` concept soon.664665666Exceptions667----------668669.. autoexception:: jinja2.TemplateError670671.. autoexception:: jinja2.UndefinedError672673.. autoexception:: jinja2.TemplateNotFound674675.. autoexception:: jinja2.TemplatesNotFound676677.. autoexception:: jinja2.TemplateSyntaxError678679    .. attribute:: message680681        The error message as utf-8 bytestring.682683    .. attribute:: lineno684685        The line number where the error occurred686687    .. attribute:: name688689        The load name for the template as unicode string.690691    .. attribute:: filename692693        The filename that loaded the template as bytestring in the encoding694        of the file system (most likely utf-8 or mbcs on Windows systems).695696    The reason why the filename and error message are bytestrings and not697    unicode strings is that Python 2.x is not using unicode for exceptions698    and tracebacks as well as the compiler.  This will change with Python 3.699700.. autoexception:: jinja2.TemplateRuntimeError701702.. autoexception:: jinja2.TemplateAssertionError703704705.. _writing-filters:706707Custom Filters708--------------709710Custom filters are just regular Python functions that take the left side of711the filter as first argument and the arguments passed to the filter as712extra arguments or keyword arguments.713714For example in the filter ``{{ 42|myfilter(23) }}`` the function would be715called with ``myfilter(42, 23)``.  Here for example a simple filter that can716be applied to datetime objects to format them::717718    def datetimeformat(value, format='%H:%M / %d-%m-%Y'):719        return value.strftime(format)720721You can register it on the template environment by updating the722:attr:`~Environment.filters` dict on the environment::723724    environment.filters['datetimeformat'] = datetimeformat725726Inside the template it can then be used as follows:727728.. sourcecode:: jinja729730    written on: {{ article.pub_date|datetimeformat }}731    publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}732733Filters can also be passed the current template context or environment.  This734is useful if a filter wants to return an undefined value or check the current735:attr:`~Environment.autoescape` setting.  For this purpose three decorators736exist: :func:`environmentfilter`, :func:`contextfilter` and737:func:`evalcontextfilter`.738739Here a small example filter that breaks a text into HTML line breaks and740paragraphs and marks the return value as safe HTML string if autoescaping is741enabled::742743    import re744    from jinja2 import evalcontextfilter, Markup, escape745746    _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')747748    @evalcontextfilter749    def nl2br(eval_ctx, value):750        result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))751                              for p in _paragraph_re.split(escape(value)))752        if eval_ctx.autoescape:753            result = Markup(result)754        return result755756Context filters work the same just that the first argument is the current757active :class:`Context` rather than the environment.758759760.. _eval-context:761762Evaluation Context763------------------764765The evaluation context (short eval context or eval ctx) is a new object766introduced in Jinja 2.4 that makes it possible to activate and deactivate767compiled features at runtime.768769Currently it is only used to enable and disable the automatic escaping but770can be used for extensions as well.771772In previous Jinja versions filters and functions were marked as773environment callables in order to check for the autoescape status from the774environment.  In new versions it's encouraged to check the setting from the775evaluation context instead.776777Previous versions::778779    @environmentfilter780    def filter(env, value):781        result = do_something(value)782        if env.autoescape:783            result = Markup(result)784        return result785786In new versions you can either use a :func:`contextfilter` and access the787evaluation context from the actual context, or use a788:func:`evalcontextfilter` which directly passes the evaluation context to789the function::790791    @contextfilter792    def filter(context, value):793        result = do_something(value)794        if context.eval_ctx.autoescape:795            result = Markup(result)796        return result797798    @evalcontextfilter799    def filter(eval_ctx, value):800        result = do_something(value)801        if eval_ctx.autoescape:802            result = Markup(result)803        return result804805The evaluation context must not be modified at runtime.  Modifications806must only happen with a :class:`nodes.EvalContextModifier` and807:class:`nodes.ScopedEvalContextModifier` from an extension, not on the808eval context object itself.809810.. autoclass:: jinja2.nodes.EvalContext811812   .. attribute:: autoescape813814      `True` or `False` depending on if autoescaping is active or not.815816   .. attribute:: volatile817818      `True` if the compiler cannot evaluate some expressions at compile819      time.  At runtime this should always be `False`.820821822.. _writing-tests:823824Custom Tests825------------826827Tests work like filters just that there is no way for a test to get access828to the environment or context and that they can't be chained.  The return829value of a test should be `True` or `False`.  The purpose of a test is to830give the template designers the possibility to perform type and conformability831checks.832833Here a simple test that checks if a variable is a prime number::834835    import math836837    def is_prime(n):838        if n == 2:839            return True840        for i in range(2, int(math.ceil(math.sqrt(n))) + 1):841            if n % i == 0:842                return False843        return True844845846You can register it on the template environment by updating the847:attr:`~Environment.tests` dict on the environment::848849    environment.tests['prime'] = is_prime850851A template designer can then use the test like this:852853.. sourcecode:: jinja854855    {% if 42 is prime %}856        42 is a prime number857    {% else %}858        42 is not a prime number859    {% endif %}860861862.. _global-namespace:863864The Global Namespace865--------------------866867Variables stored in the :attr:`Environment.globals` dict are special as they868are available for imported templates too, even if they are imported without869context.  This is the place where you can put variables and functions870that should be available all the time.  Additionally :attr:`Template.globals`871exist that are variables available to a specific template that are available872to all :meth:`~Template.render` calls.873874875.. _low-level-api:876877Low Level API878-------------879880The low level API exposes functionality that can be useful to understand some881implementation details, debugging purposes or advanced :ref:`extension882<jinja-extensions>` techniques.  Unless you know exactly what you are doing we883don't recommend using any of those.884885.. automethod:: Environment.lex886887.. automethod:: Environment.parse888889.. automethod:: Environment.preprocess890891.. automethod:: Template.new_context892893.. method:: Template.root_render_func(context)894895    This is the low level render function.  It's passed a :class:`Context`896    that has to be created by :meth:`new_context` of the same template or897    a compatible template.  This render function is generated by the898    compiler from the template code and returns a generator that yields899    unicode strings.900901    If an exception in the template code happens the template engine will902    not rewrite the exception but pass through the original one.  As a903    matter of fact this function should only be called from within a904    :meth:`render` / :meth:`generate` / :meth:`stream` call.905906.. attribute:: Template.blocks907908    A dict of block render functions.  Each of these functions works exactly909    like the :meth:`root_render_func` with the same limitations.910911.. attribute:: Template.is_up_to_date912913    This attribute is `False` if there is a newer version of the template914    available, otherwise `True`.915916.. admonition:: Note917918    The low-level API is fragile.  Future Jinja versions will try not to919    change it in a backwards incompatible way but modifications in the Jinja920    core may shine through.  For example if Jinja introduces a new AST node921    in later versions that may be returned by :meth:`~Environment.parse`.922923The Meta API924------------925926.. versionadded:: 2.2927928The meta API returns some information about abstract syntax trees that929could help applications to implement more advanced template concepts.  All930the functions of the meta API operate on an abstract syntax tree as931returned by the :meth:`Environment.parse` method.932933.. autofunction:: jinja2.meta.find_undeclared_variables934935.. autofunction:: jinja2.meta.find_referenced_templates