1API 2=== 3 4.. module:: jinja2 5 :noindex: 6 :synopsis: public Jinja API 7 8This document describes the API to Jinja and not the template language 9(for that, see :doc:`/templates`). It will be most useful as reference 10to those implementing the template interface to the application and not 11those who are creating Jinja templates. 12 13Basics 14------ 15 16Jinja 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 of 20:class:`Template` class, an environment is created automatically for you, 21albeit a shared one. 22 23Most applications will create one :class:`Environment` object on application 24initialization and use that to load templates. In some cases however, it's 25useful to have multiple environments side by side, if different configurations 26are in use. 27 28The simplest way to configure Jinja to load templates for your 29application is to use :class:`~loaders.PackageLoader`. 30 31.. code-block:: python 32 33 from jinja2 import Environment, PackageLoader, select_autoescape 34 env = Environment( 35 loader=PackageLoader("yourapp"), 36 autoescape=select_autoescape() 37 ) 38 39This will create a template environment with a loader that looks up 40templates in the ``templates`` folder inside the ``yourapp`` Python 41package (or next to the ``yourapp.py`` Python module). It also enables 42autoescaping for HTML files. This loader only requires that ``yourapp`` 43is importable, it figures out the absolute path to the folder for you. 44 45Different loaders are available to load templates in other ways or from 46other locations. They're listed in the `Loaders`_ section below. You can 47also write your own if you want to load templates from a source that's 48more specialized to your project. 49 50To load a template from this environment, call the :meth:`get_template` 51method, which returns the loaded :class:`Template`. 52 53.. code-block:: python 54 55 template = env.get_template("mytemplate.html") 56 57To render it with some variables, call the :meth:`render` method. 58 59.. code-block:: python 60 61 print(template.render(the="variables", go="here")) 62 63Using a template loader rather than passing strings to :class:`Template` 64or :meth:`Environment.from_string` has multiple advantages. Besides being 65a lot easier to use it also enables template inheritance. 66 67.. admonition:: Notes on Autoescaping 68 69 In future versions of Jinja we might enable autoescaping by default 70 for security reasons. As such you are encouraged to explicitly 71 configure autoescaping now instead of relying on the default. 72 73 74High Level API 75-------------- 76 77The high-level API is the API you will use in the application to load and 78render Jinja templates. The :ref:`low-level-api` on the other side is only 79useful if you want to dig deeper into Jinja or :ref:`develop extensions 80<jinja-extensions>`. 81 82.. autoclass:: Environment([options]) 83 :members: from_string, get_template, select_template, 84 get_or_select_template, join_path, extend, compile_expression, 85 compile_templates, list_templates, add_extension 86 87 .. attribute:: shared 88 89 If a template was created by using the :class:`Template` constructor 90 an environment is created automatically. These environments are 91 created as shared environments which means that multiple templates 92 may have the same anonymous environment. For all shared environments 93 this attribute is `True`, else `False`. 94 95 .. attribute:: sandboxed 96 97 If the environment is sandboxed this attribute is `True`. For the 98 sandbox mode have a look at the documentation for the 99 :class:`~jinja2.sandbox.SandboxedEnvironment`. 100 101 .. attribute:: filters 102 103 A dict of filters for this environment. As long as no template was 104 loaded it's safe to add new filters or remove old. For custom filters 105 see :ref:`writing-filters`. For valid filter names have a look at 106 :ref:`identifier-naming`. 107 108 .. attribute:: tests 109 110 A dict of test functions for this environment. As long as no 111 template was loaded it's safe to modify this dict. For custom tests 112 see :ref:`writing-tests`. For valid test names have a look at 113 :ref:`identifier-naming`. 114 115 .. attribute:: globals 116 117 A dict of global variables. These variables are always available 118 in a template. As long as no template was loaded it's safe 119 to modify this dict. For more details see :ref:`global-namespace`. 120 For valid object names have a look at :ref:`identifier-naming`. 121 122 .. attribute:: policies 123 124 A dictionary with :ref:`policies`. These can be reconfigured to 125 change the runtime behavior or certain template features. Usually 126 these are security related. 127 128 .. attribute:: code_generator_class 129 130 The class used for code generation. This should not be changed 131 in most cases, unless you need to modify the Python code a 132 template compiles to. 133 134 .. attribute:: context_class 135 136 The context used for templates. This should not be changed 137 in most cases, unless you need to modify internals of how 138 template variables are handled. For details, see 139 :class:`~jinja2.runtime.Context`. 140 141 .. automethod:: overlay([options]) 142 143 .. method:: undefined([hint, obj, name, exc]) 144 145 Creates a new :class:`Undefined` object for `name`. This is useful 146 for filters or functions that may return undefined objects for 147 some operations. All parameters except of `hint` should be provided 148 as keyword parameters for better readability. The `hint` is used as 149 error message for the exception if provided, otherwise the error 150 message will be generated from `obj` and `name` automatically. The exception 151 provided as `exc` is raised if something with the generated undefined 152 object is done that the undefined object does not allow. The default 153 exception is :exc:`UndefinedError`. If a `hint` is provided the 154 `name` may be omitted. 155 156 The most common way to create an undefined object is by providing 157 a name only:: 158 159 return environment.undefined(name='some_name') 160 161 This means that the name `some_name` is not defined. If the name 162 was from an attribute of an object it makes sense to tell the 163 undefined object the holder object to improve the error message:: 164 165 if not hasattr(obj, 'attr'): 166 return environment.undefined(obj=obj, name='attr') 167 168 For a more complex example you can provide a hint. For example 169 the :func:`first` filter creates an undefined object that way:: 170 171 return environment.undefined('no first item, sequence was empty') 172 173 If it the `name` or `obj` is known (for example because an attribute 174 was accessed) it should be passed to the undefined object, even if 175 a custom `hint` is provided. This gives undefined objects the 176 possibility to enhance the error message. 177 178.. autoclass:: Template 179 :members: module, make_module 180 181 .. attribute:: globals 182 183 The dict with the globals of that template. It's unsafe to modify 184 this dict as it may be shared with other templates or the environment 185 that loaded the template. 186 187 .. attribute:: name 188 189 The loading name of the template. If the template was loaded from a 190 string this is `None`. 191 192 .. attribute:: filename 193 194 The filename of the template on the file system if it was loaded from 195 there. Otherwise this is `None`. 196 197 .. automethod:: render([context]) 198 199 .. automethod:: generate([context]) 200 201 .. automethod:: stream([context]) 202 203 .. automethod:: render_async([context]) 204 205 .. automethod:: generate_async([context]) 206 207 208.. autoclass:: jinja2.environment.TemplateStream() 209 :members: disable_buffering, enable_buffering, dump 210 211 212Autoescaping 213------------ 214 215.. versionchanged:: 2.4 216 217Jinja now comes with autoescaping support. As of Jinja 2.9 the 218autoescape extension is removed and built-in. However autoescaping is 219not yet enabled by default though this will most likely change in the 220future. It's recommended to configure a sensible default for 221autoescaping. This makes it possible to enable and disable autoescaping 222on a per-template basis (HTML versus text for instance). 223 224.. autofunction:: jinja2.select_autoescape 225 226Here a recommended setup that enables autoescaping for templates ending 227in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default 228for all other extensions. You can use the :func:`~jinja2.select_autoescape` 229function for this:: 230 231 from jinja2 import Environment, select_autoescape 232 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']), 233 loader=PackageLoader('mypackage')) 234 235The :func:`~jinja.select_autoescape` function returns a function that 236works roughly like this:: 237 238 def autoescape(template_name): 239 if template_name is None: 240 return False 241 if template_name.endswith(('.html', '.htm', '.xml')) 242 243When implementing a guessing autoescape function, make sure you also 244accept `None` as valid template name. This will be passed when generating 245templates from strings. You should always configure autoescaping as 246defaults in the future might change. 247 248Inside the templates the behaviour can be temporarily changed by using 249the `autoescape` block (see :ref:`autoescape-overrides`). 250 251 252.. _identifier-naming: 253 254Notes on Identifiers 255-------------------- 256 257Jinja uses Python naming rules. Valid identifiers can be any combination 258of characters accepted by Python. 259 260Filters and tests are looked up in separate namespaces and have slightly 261modified identifier syntax. Filters and tests may contain dots to group 262filters and tests by topic. For example it's perfectly valid to add a 263function into the filter dict and call it `to.str`. The regular 264expression for filter and test identifiers is 265``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. 266 267 268Undefined Types 269--------------- 270 271These classes can be used as undefined types. The :class:`Environment` 272constructor takes an `undefined` parameter that can be one of those classes 273or a custom subclass of :class:`Undefined`. Whenever the template engine is 274unable to look up a name or access an attribute one of those objects is 275created and returned. Some operations on undefined values are then allowed, 276others fail. 277 278The closest to regular Python behavior is the :class:`StrictUndefined` which 279disallows all operations beside testing if it's an undefined object. 280 281.. autoclass:: jinja2.Undefined() 282 283 .. attribute:: _undefined_hint 284 285 Either `None` or a string with the error message for the 286 undefined object. 287 288 .. attribute:: _undefined_obj 289 290 Either `None` or the owner object that caused the undefined object 291 to be created (for example because an attribute does not exist). 292 293 .. attribute:: _undefined_name 294 295 The name for the undefined variable / attribute or just `None` 296 if no such information exists. 297 298 .. attribute:: _undefined_exception 299 300 The exception that the undefined object wants to raise. This 301 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`. 302 303 .. method:: _fail_with_undefined_error(\*args, \**kwargs) 304 305 When called with any arguments this method raises 306 :attr:`_undefined_exception` with an error message generated 307 from the undefined hints stored on the undefined object. 308 309.. autoclass:: jinja2.ChainableUndefined() 310 311.. autoclass:: jinja2.DebugUndefined() 312 313.. autoclass:: jinja2.StrictUndefined() 314 315There is also a factory function that can decorate undefined objects to 316implement logging on failures: 317 318.. autofunction:: jinja2.make_logging_undefined 319 320Undefined objects are created by calling :attr:`undefined`. 321 322.. admonition:: Implementation 323 324 :class:`Undefined` is implemented by overriding the special 325 ``__underscore__`` methods. For example the default 326 :class:`Undefined` class implements ``__str__`` to returns an empty 327 string, while ``__int__`` and others fail with an exception. To 328 allow conversion to int by returning ``0`` you can implement your 329 own subclass. 330 331 .. code-block:: python 332 333 class NullUndefined(Undefined): 334 def __int__(self): 335 return 0 336 337 def __float__(self): 338 return 0.0 339 340 To disallow a method, override it and raise 341 :attr:`~Undefined._undefined_exception`. Because this is very 342 common there is the helper method 343 :meth:`~Undefined._fail_with_undefined_error` that raises the error 344 with the correct information. Here's a class that works like the 345 regular :class:`Undefined` but fails on iteration:: 346 347 class NonIterableUndefined(Undefined): 348 def __iter__(self): 349 self._fail_with_undefined_error() 350 351 352The Context 353----------- 354 355.. autoclass:: jinja2.runtime.Context() 356 :members: resolve, get_exported, get_all 357 358 .. attribute:: parent 359 360 A dict of read only, global variables the template looks up. These 361 can either come from another :class:`Context`, from the 362 :attr:`Environment.globals` or :attr:`Template.globals` or points 363 to a dict created by combining the globals with the variables 364 passed to the render function. It must not be altered. 365 366 .. attribute:: vars 367 368 The template local variables. This list contains environment and 369 context functions from the :attr:`parent` scope as well as local 370 modifications and exported variables from the template. The template 371 will modify this dict during template evaluation but filters and 372 context functions are not allowed to modify it. 373 374 .. attribute:: environment 375 376 The environment that loaded the template. 377 378 .. attribute:: exported_vars 379 380 This set contains all the names the template exports. The values for 381 the names are in the :attr:`vars` dict. In order to get a copy of the 382 exported variables as dict, :meth:`get_exported` can be used. 383 384 .. attribute:: name 385 386 The load name of the template owning this context. 387 388 .. attribute:: blocks 389 390 A dict with the current mapping of blocks in the template. The keys 391 in this dict are the names of the blocks, and the values a list of 392 blocks registered. The last item in each list is the current active 393 block (latest in the inheritance chain). 394 395 .. attribute:: eval_ctx 396 397 The current :ref:`eval-context`. 398 399 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs) 400 401 402.. admonition:: Implementation 403 404 Context is immutable for the same reason Python's frame locals are 405 immutable inside functions. Both Jinja and Python are not using the 406 context / frame locals as data storage for variables but only as primary 407 data source. 408 409 When a template accesses a variable the template does not define, Jinja 410 looks up the variable in the context, after that the variable is treated 411 as if it was defined in the template. 412 413 414.. _loaders: 415 416Loaders 417------- 418 419Loaders are responsible for loading templates from a resource such as the 420file system. The environment will keep the compiled modules in memory like 421Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in 422size by default and templates are automatically reloaded. 423All loaders are subclasses of :class:`BaseLoader`. If you want to create your 424own loader, subclass :class:`BaseLoader` and override `get_source`. 425 426.. autoclass:: jinja2.BaseLoader 427 :members: get_source, load 428 429Here a list of the builtin loaders Jinja provides: 430 431.. autoclass:: jinja2.FileSystemLoader 432 433.. autoclass:: jinja2.PackageLoader 434 435.. autoclass:: jinja2.DictLoader 436 437.. autoclass:: jinja2.FunctionLoader 438 439.. autoclass:: jinja2.PrefixLoader 440 441.. autoclass:: jinja2.ChoiceLoader 442 443.. autoclass:: jinja2.ModuleLoader 444 445 446.. _bytecode-cache: 447 448Bytecode Cache 449-------------- 450 451Jinja 2.1 and higher support external bytecode caching. Bytecode caches make 452it possible to store the generated bytecode on the file system or a different 453location to avoid parsing the templates on first use. 454 455This is especially useful if you have a web application that is initialized on 456the first request and Jinja compiles many templates at once which slows down 457the application. 458 459To use a bytecode cache, instantiate it and pass it to the :class:`Environment`. 460 461.. autoclass:: jinja2.BytecodeCache 462 :members: load_bytecode, dump_bytecode, clear 463 464.. autoclass:: jinja2.bccache.Bucket 465 :members: write_bytecode, load_bytecode, bytecode_from_string, 466 bytecode_to_string, reset 467 468 .. attribute:: environment 469 470 The :class:`Environment` that created the bucket. 471 472 .. attribute:: key 473 474 The unique cache key for this bucket 475 476 .. attribute:: code 477 478 The bytecode if it's loaded, otherwise `None`. 479 480 481Builtin bytecode caches: 482 483.. autoclass:: jinja2.FileSystemBytecodeCache 484 485.. autoclass:: jinja2.MemcachedBytecodeCache 486 487 488Async Support 489------------- 490 491.. versionadded:: 2.9 492 493Jinja supports the Python ``async`` and ``await`` syntax. For the 494template designer, this support (when enabled) is entirely transparent, 495templates continue to look exactly the same. However, developers should 496be aware of the implementation as it affects what types of APIs you can 497use. 498 499By default, async support is disabled. Enabling it will cause the 500environment to compile different code behind the scenes in order to 501handle async and sync code in an asyncio event loop. This has the 502following implications: 503 504- Template rendering requires an event loop to be available to the 505 current thread. :func:`asyncio.get_event_loop` must return an event 506 loop. 507- The compiled code uses ``await`` for functions and attributes, and 508 uses ``async for`` loops. In order to support using both async and 509 sync functions in this context, a small wrapper is placed around 510 all calls and access, which add overhead compared to purely async 511 code. 512- Sync methods and filters become wrappers around their corresponding 513 async implementations where needed. For example, ``render`` invokes 514 ``async_render``, and ``|map`` supports async iterables. 515 516Awaitable objects can be returned from functions in templates and any 517function call in a template will automatically await the result. The 518``await`` you would normally add in Python is implied. For example, you 519can provide a method that asynchronously loads data from a database, and 520from the template designer's point of view it can be called like any 521other function. 522 523 524.. _policies: 525 526Policies 527-------- 528 529Starting with Jinja 2.9 policies can be configured on the environment 530which can slightly influence how filters and other template constructs 531behave. They can be configured with the 532:attr:`~jinja2.Environment.policies` attribute. 533 534Example:: 535 536 env.policies['urlize.rel'] = 'nofollow noopener' 537 538``truncate.leeway``: 539 Configures the leeway default for the `truncate` filter. Leeway as 540 introduced in 2.9 but to restore compatibility with older templates 541 it can be configured to `0` to get the old behavior back. The default 542 is `5`. 543 544``urlize.rel``: 545 A string that defines the items for the `rel` attribute of generated 546 links with the `urlize` filter. These items are always added. The 547 default is `noopener`. 548 549``urlize.target``: 550 The default target that is issued for links from the `urlize` filter 551 if no other target is defined by the call explicitly. 552 553``json.dumps_function``: 554 If this is set to a value other than `None` then the `tojson` filter 555 will dump with this function instead of the default one. Note that 556 this function should accept arbitrary extra arguments which might be 557 passed in the future from the filter. Currently the only argument 558 that might be passed is `indent`. The default dump function is 559 ``json.dumps``. 560 561``json.dumps_kwargs``: 562 Keyword arguments to be passed to the dump function. The default is 563 ``{'sort_keys': True}``. 564 565.. _ext-i18n-trimmed: 566 567``ext.i18n.trimmed``: 568 If this is set to `True`, ``{% trans %}`` blocks of the 569 :ref:`i18n-extension` will always unify linebreaks and surrounding 570 whitespace as if the `trimmed` modifier was used. 571 572 573Utilities 574--------- 575 576These helper functions and classes are useful if you add custom filters or 577functions to a Jinja environment. 578 579.. autofunction:: jinja2.environmentfilter 580 581.. autofunction:: jinja2.contextfilter 582 583.. autofunction:: jinja2.evalcontextfilter 584 585.. autofunction:: jinja2.environmentfunction 586 587.. autofunction:: jinja2.contextfunction 588 589.. autofunction:: jinja2.evalcontextfunction 590 591.. function:: escape(s) 592 593 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s` 594 to HTML-safe sequences. Use this if you need to display text that might 595 contain such characters in HTML. This function will not escaped objects 596 that do have an HTML representation such as already escaped data. 597 598 The return value is a :class:`Markup` string. 599 600.. autofunction:: jinja2.clear_caches 601 602.. autofunction:: jinja2.is_undefined 603 604.. autoclass:: jinja2.Markup([string]) 605 :members: escape, unescape, striptags 606 607.. admonition:: Note 608 609 The Jinja :class:`Markup` class is compatible with at least Pylons and 610 Genshi. It's expected that more template engines and framework will pick 611 up the `__html__` concept soon. 612 613 614Exceptions 615---------- 616 617.. autoexception:: jinja2.TemplateError 618 619.. autoexception:: jinja2.UndefinedError 620 621.. autoexception:: jinja2.TemplateNotFound 622 623.. autoexception:: jinja2.TemplatesNotFound 624 625.. autoexception:: jinja2.TemplateSyntaxError 626 627 .. attribute:: message 628 629 The error message. 630 631 .. attribute:: lineno 632 633 The line number where the error occurred. 634 635 .. attribute:: name 636 637 The load name for the template. 638 639 .. attribute:: filename 640 641 The filename that loaded the template in the encoding of the 642 file system (most likely utf-8, or mbcs on Windows systems). 643 644.. autoexception:: jinja2.TemplateRuntimeError 645 646.. autoexception:: jinja2.TemplateAssertionError 647 648 649.. _writing-filters: 650 651Custom Filters 652-------------- 653 654Custom filters are just regular Python functions that take the left side of 655the filter as first argument and the arguments passed to the filter as 656extra arguments or keyword arguments. 657 658For example in the filter ``{{ 42|myfilter(23) }}`` the function would be 659called with ``myfilter(42, 23)``. Here for example a simple filter that can 660be applied to datetime objects to format them:: 661 662 def datetimeformat(value, format='%H:%M / %d-%m-%Y'): 663 return value.strftime(format) 664 665You can register it on the template environment by updating the 666:attr:`~Environment.filters` dict on the environment:: 667 668 environment.filters['datetimeformat'] = datetimeformat 669 670Inside the template it can then be used as follows: 671 672.. sourcecode:: jinja 673 674 written on: {{ article.pub_date|datetimeformat }} 675 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} 676 677Filters can also be passed the current template context or environment. This 678is useful if a filter wants to return an undefined value or check the current 679:attr:`~Environment.autoescape` setting. For this purpose three decorators 680exist: :func:`environmentfilter`, :func:`contextfilter` and 681:func:`evalcontextfilter`. 682 683Here a small example filter that breaks a text into HTML line breaks and 684paragraphs and marks the return value as safe HTML string if autoescaping is 685enabled:: 686 687 import re 688 from jinja2 import evalcontextfilter, Markup, escape 689 690 _paragraph_re = re.compile(r"(?:\r\n|\r(?!\n)|\n){2,}") 691 692 @evalcontextfilter 693 def nl2br(eval_ctx, value): 694 result = "\n\n".join( 695 f"<p>{p.replace('\n', Markup('<br>\n'))}</p>" 696 for p in _paragraph_re.split(escape(value)) 697 ) 698 if eval_ctx.autoescape: 699 result = Markup(result) 700 return result 701 702Context filters work the same just that the first argument is the current 703active :class:`Context` rather than the environment. 704 705 706.. _eval-context: 707 708Evaluation Context 709------------------ 710 711The evaluation context (short eval context or eval ctx) is a new object 712introduced in Jinja 2.4 that makes it possible to activate and deactivate 713compiled features at runtime. 714 715Currently it is only used to enable and disable the automatic escaping but 716can be used for extensions as well. 717 718In previous Jinja versions filters and functions were marked as 719environment callables in order to check for the autoescape status from the 720environment. In new versions it's encouraged to check the setting from the 721evaluation context instead. 722 723Previous versions:: 724 725 @environmentfilter 726 def filter(env, value): 727 result = do_something(value) 728 if env.autoescape: 729 result = Markup(result) 730 return result 731 732In new versions you can either use a :func:`contextfilter` and access the 733evaluation context from the actual context, or use a 734:func:`evalcontextfilter` which directly passes the evaluation context to 735the function:: 736 737 @contextfilter 738 def filter(context, value): 739 result = do_something(value) 740 if context.eval_ctx.autoescape: 741 result = Markup(result) 742 return result 743 744 @evalcontextfilter 745 def filter(eval_ctx, value): 746 result = do_something(value) 747 if eval_ctx.autoescape: 748 result = Markup(result) 749 return result 750 751The evaluation context must not be modified at runtime. Modifications 752must only happen with a :class:`nodes.EvalContextModifier` and 753:class:`nodes.ScopedEvalContextModifier` from an extension, not on the 754eval context object itself. 755 756.. autoclass:: jinja2.nodes.EvalContext 757 758 .. attribute:: autoescape 759 760 `True` or `False` depending on if autoescaping is active or not. 761 762 .. attribute:: volatile 763 764 `True` if the compiler cannot evaluate some expressions at compile 765 time. At runtime this should always be `False`. 766 767 768.. _writing-tests: 769 770Custom Tests 771------------ 772 773Tests work like filters just that there is no way for a test to get access 774to the environment or context and that they can't be chained. The return 775value of a test should be `True` or `False`. The purpose of a test is to 776give the template designers the possibility to perform type and conformability 777checks. 778 779Here a simple test that checks if a variable is a prime number:: 780 781 import math 782 783 def is_prime(n): 784 if n == 2: 785 return True 786 for i in range(2, int(math.ceil(math.sqrt(n))) + 1): 787 if n % i == 0: 788 return False 789 return True 790 791 792You can register it on the template environment by updating the 793:attr:`~Environment.tests` dict on the environment:: 794 795 environment.tests['prime'] = is_prime 796 797A template designer can then use the test like this: 798 799.. sourcecode:: jinja 800 801 {% if 42 is prime %} 802 42 is a prime number 803 {% else %} 804 42 is not a prime number 805 {% endif %} 806 807 808.. _global-namespace: 809 810The Global Namespace 811-------------------- 812 813Variables stored in the :attr:`Environment.globals` dict are special as they 814are available for imported templates too, even if they are imported without 815context. This is the place where you can put variables and functions 816that should be available all the time. Additionally :attr:`Template.globals` 817exist that are variables available to a specific template that are available 818to all :meth:`~Template.render` calls. 819 820 821.. _low-level-api: 822 823Low Level API 824------------- 825 826The low level API exposes functionality that can be useful to understand some 827implementation details, debugging purposes or advanced :ref:`extension 828<jinja-extensions>` techniques. Unless you know exactly what you are doing we 829don't recommend using any of those. 830 831.. automethod:: Environment.lex 832 833.. automethod:: Environment.parse 834 835.. automethod:: Environment.preprocess 836 837.. automethod:: Template.new_context 838 839.. method:: Template.root_render_func(context) 840 841 This is the low level render function. It's passed a :class:`Context` 842 that has to be created by :meth:`new_context` of the same template or 843 a compatible template. This render function is generated by the 844 compiler from the template code and returns a generator that yields 845 strings. 846 847 If an exception in the template code happens the template engine will 848 not rewrite the exception but pass through the original one. As a 849 matter of fact this function should only be called from within a 850 :meth:`render` / :meth:`generate` / :meth:`stream` call. 851 852.. attribute:: Template.blocks 853 854 A dict of block render functions. Each of these functions works exactly 855 like the :meth:`root_render_func` with the same limitations. 856 857.. attribute:: Template.is_up_to_date 858 859 This attribute is `False` if there is a newer version of the template 860 available, otherwise `True`. 861 862.. admonition:: Note 863 864 The low-level API is fragile. Future Jinja versions will try not to 865 change it in a backwards incompatible way but modifications in the Jinja 866 core may shine through. For example if Jinja introduces a new AST node 867 in later versions that may be returned by :meth:`~Environment.parse`. 868 869The Meta API 870------------ 871 872.. versionadded:: 2.2 873 874The meta API returns some information about abstract syntax trees that 875could help applications to implement more advanced template concepts. All 876the functions of the meta API operate on an abstract syntax tree as 877returned by the :meth:`Environment.parse` method. 878 879.. autofunction:: jinja2.meta.find_undeclared_variables 880 881.. autofunction:: jinja2.meta.find_referenced_templates 882