Skip to content
Myr

use "Jinja" instead of "Jinja2"

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 6e50bbd · Browse files · 30 files+158 added−160 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

30 files+158 added−160 removed

  • other:+158 added−160 removed

30 files+158 added−160 removed

modified:docs/api.rst+28 added-30 removed
1 unmodified line
2===34.. module:: jinja25 :noindex:6 :synopsis: public Jinja2 API6 :synopsis: public Jinja API78This document describes the API to Jinja2 and not the template language. It8This document describes the API to Jinja and not the template language. It9will be most useful as reference to those implementing the template interface10to the application and not those who are creating Jinja2 templates.10to the application and not those who are creating Jinja templates.1112Basics13------1415Jinja2 uses a central object called the template :class:`Environment`.15Jinja uses a central object called the template :class:`Environment`.16Instances of this class are used to store the configuration and global objects,17and are used to load templates from the file system or other locations.18Even if you are creating templates from strings by using the constructor of19:class:`Template` class, an environment is created automatically for you,
3 unmodified lines
23initialization and use that to load templates. In some cases however, it's24useful to have multiple environments side by side, if different configurations25are in use.2627The simplest way to configure Jinja2 to load templates for your application27The simplest way to configure Jinja to load templates for your application28looks roughly like this::2930 from jinja2 import Environment, PackageLoader, select_autoescape31 env = Environment(
22 unmodified lines
54a lot easier to use it also enables template inheritance.5556.. admonition:: Notes on Autoescaping5758 In future versions of Jinja2 we might enable autoescaping by default58 In future versions of Jinja we might enable autoescaping by default59 for security reasons. As such you are encouraged to explicitly60 configure autoescaping now instead of relying on the default.616263Unicode64-------6566Jinja2 is using Unicode internally which means that you have to pass Unicode66Jinja is using Unicode internally which means that you have to pass Unicode67objects to the render function or bytestrings that only consist of ASCII68characters. Additionally newlines are normalized to one end of line69sequence which is per default UNIX style (``\n``).70
16 unmodified lines
87 # -*- coding: utf-8 -*-8889We recommend utf-8 as Encoding for Python modules and templates as it's90possible to represent every Unicode character in utf-8 and because it's91backwards compatible to ASCII. For Jinja2 the default encoding of templates91backwards compatible to ASCII. For Jinja the default encoding of templates92is assumed to be utf-8.9394It is not possible to use Jinja2 to process non-Unicode data. The reason95for this is that Jinja2 uses Unicode already on the language level. For96example Jinja2 treats the non-breaking space as valid whitespace inside94It is not possible to use Jinja to process non-Unicode data. The reason95for this is that Jinja uses Unicode already on the language level. For96example Jinja treats the non-breaking space as valid whitespace inside97expressions which requires knowledge of the encoding or operating on an98Unicode string.99100For more details about Unicode in Python have a look at the excellent101`Unicode documentation`_.102103Another important thing is how Jinja2 is handling string literals in103Another important thing is how Jinja is handling string literals in104templates. A naive implementation would be using Unicode strings for105all string literals but it turned out in the past that this is problematic106as some libraries are typechecking against `str` explicitly. For example107`datetime.strftime` does not accept Unicode arguments. To not break it108completely Jinja2 is returning `str` for strings that fit into ASCII and108completely Jinja is returning `str` for strings that fit into ASCII and109for everything else `unicode`:110111>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module112>>> m.a
7 unmodified lines
120High Level API121--------------122123The high-level API is the API you will use in the application to load and124render Jinja2 templates. The :ref:`low-level-api` on the other side is only125useful if you want to dig deeper into Jinja2 or :ref:`develop extensions124render Jinja templates. The :ref:`low-level-api` on the other side is only125useful if you want to dig deeper into Jinja or :ref:`develop extensions126<jinja-extensions>`.127128.. autoclass:: Environment([options])129 :members: from_string, get_template, select_template,
129 unmodified lines
259------------260261.. versionchanged:: 2.4262263Jinja2 now comes with autoescaping support. As of Jinja 2.9 the263Jinja now comes with autoescaping support. As of Jinja 2.9 the264autoescape extension is removed and built-in. However autoescaping is265not yet enabled by default though this will most likely change in the266future. It's recommended to configure a sensible default for267autoescaping. This makes it possible to enable and disable autoescaping
31 unmodified lines
299300Notes on Identifiers301--------------------302303Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to304match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters305are currently not allowed. This limitation will probably go away as soon as306unicode identifiers are fully specified for Python 3.303Jinja uses Python naming rules. Valid identifiers can be any combination304of Unicode characters accepted by Python.305306Filters and tests are looked up in separate namespaces and have slightly307modified identifier syntax. Filters and tests may contain dots to group308filters and tests by topic. For example it's perfectly valid to add a
133 unmodified lines
442443.. admonition:: Implementation444445 Context is immutable for the same reason Python's frame locals are448 immutable inside functions. Both Jinja2 and Python are not using the446 immutable inside functions. Both Jinja and Python are not using the447 context / frame locals as data storage for variables but only as primary448 data source.449452 When a template accesses a variable the template does not define, Jinja2450 When a template accesses a variable the template does not define, Jinja451 looks up the variable in the context, after that the variable is treated452 as if it was defined in the template.453454
11 unmodified lines
466467.. autoclass:: jinja2.BaseLoader468 :members: get_source, load469472Here a list of the builtin loaders Jinja2 provides:470Here a list of the builtin loaders Jinja provides:471472.. autoclass:: jinja2.FileSystemLoader473474.. autoclass:: jinja2.PackageLoader
53 unmodified lines
528529Async Support530-------------531534Starting with version 2.9, Jinja2 also supports the Python `async` and532Starting with version 2.9, Jinja also supports the Python `async` and533`await` constructs. As far as template designers go this feature is534entirely opaque to them however as a developer you should be aware of how535it's implemented as it influences what type of APIs you can safely expose536to the template environment.
38 unmodified lines
575576 env.policies['urlize.rel'] = 'nofollow noopener'577578``compiler.ascii_str``:581 This boolean controls on Python 2 if Jinja2 should store ASCII only579 This boolean controls on Python 2 if Jinja should store ASCII only580 literals as bytestring instead of unicode strings. This used to be581 always enabled for Jinja versions below 2.9 and now can be changed.582 Traditionally it was done this way since some APIs in Python 2 failed583 badly for unicode strings (for instance the datetime strftime API).
39 unmodified lines
623Utilities624---------625626These helper functions and classes are useful if you add custom filters or629functions to a Jinja2 environment.627functions to a Jinja environment.628629.. autofunction:: jinja2.environmentfilter630631.. autofunction:: jinja2.contextfilter
23 unmodified lines
655 :members: escape, unescape, striptags656657.. admonition:: Note658661 The Jinja2 :class:`Markup` class is compatible with at least Pylons and659 The Jinja :class:`Markup` class is compatible with at least Pylons and660 Genshi. It's expected that more template engines and framework will pick661 up the `__html__` concept soon.662663
248 unmodified lines
912 available, otherwise `True`.913914.. admonition:: Note915918 The low-level API is fragile. Future Jinja2 versions will try not to919 change it in a backwards incompatible way but modifications in the Jinja2920 core may shine through. For example if Jinja2 introduces a new AST node916 The low-level API is fragile. Future Jinja versions will try not to917 change it in a backwards incompatible way but modifications in the Jinja918 core may shine through. For example if Jinja introduces a new AST node919 in later versions that may be returned by :meth:`~Environment.parse`.920921The Meta API922------------
11 unmodified lines
modified:docs/extensions.rst+8 added-8 removed
1 unmodified line
23Extensions4==========56Jinja2 supports extensions that can add extra filters, tests, globals or even6Jinja supports extensions that can add extra filters, tests, globals or even7extend the parser. The main motivation of extensions is to move often used8code into a reusable class like adding support for internationalization.91011Adding Extensions12-----------------1314Extensions are added to the Jinja2 environment at creation time. Once the14Extensions are added to the Jinja environment at creation time. Once the15environment is created additional extensions cannot be added. To add an16extension pass a list of extension classes or import paths to the17``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following18example creates a Jinja2 environment with the i18n extension loaded::18example creates a Jinja environment with the i18n extension loaded::1920 jinja_env = Environment(extensions=['jinja2.ext.i18n'])2122
172 unmodified lines
195196**Import name:** ``jinja2.ext.loopcontrols``197198This extension adds support for ``break`` and ``continue`` in loops. After199enabling, Jinja2 provides those two keywords which work exactly like in199enabling, Jinja provides those two keywords which work exactly like in200Python.201202.. _with-extension:203
37 unmodified lines
241------------------242243.. module:: jinja2.ext244245By writing extensions you can add custom tags to Jinja2. This is a non-trivial245By writing extensions you can add custom tags to Jinja. This is a non-trivial246task and usually not needed as the default tags and expressions cover all247common use cases. The i18n extension is a good example of why extensions are248useful. Another one would be fragment caching.249250When writing extensions you have to keep in mind that you are working with the251Jinja2 template compiler which does not validate the node tree you are passing251Jinja template compiler which does not validate the node tree you are passing252to it. If the AST is malformed you will get all kinds of compiler or runtime253errors that are horrible to debug. Always make sure you are using the nodes254you create correctly. The API documentation below shows which nodes exist and255how to use them.256257Example Extension258~~~~~~~~~~~~~~~~~259260The following example implements a ``cache`` tag for Jinja2 by using the260The following example implements a ``cache`` tag for Jinja by using the261`cachelib`_ library:262263.. literalinclude:: cache_extension.py264 :language: python
99 unmodified lines
364code objects. Extensions that provide custom statements can return nodes to365execute custom Python code.366367The list below describes all nodes that are currently available. The AST may368change between Jinja2 versions but will stay backwards compatible.368change between Jinja versions but will stay backwards compatible.369370For more information have a look at the repr of :meth:`jinja2.Environment.parse`.371372.. module:: jinja2.nodes
4 unmodified lines
modified:docs/faq.rst+12 added-12 removed
16 unmodified lines
1718We really hate benchmarks especially since they don't reflect much. The19performance of a template depends on many factors and you would have to20benchmark different engines in different situations. The benchmarks from the21testsuite show that Jinja2 has a similar performance to `Mako`_ and is between21testsuite show that Jinja has a similar performance to `Mako`_ and is between2210 and 20 times faster than Django's template engine or Genshi. These numbers23should be taken with tons of salt as the benchmarks that took these numbers24only test a few performance related situations such as looping. Generally25speaking the performance of a template engine doesn't matter much as the
1 unmodified line
27code.2829.. _Mako: https://www.makotemplates.org/3031How Compatible is Jinja2 with Django?32-------------------------------------31How Compatible is Jinja with Django?32------------------------------------3334The default syntax of Jinja2 matches Django syntax in many ways. However34The default syntax of Jinja matches Django syntax in many ways. However35this similarity doesn't mean that you can use a Django template unmodified36in Jinja2. For example filter arguments use a function call syntax rather36in Jinja. For example filter arguments use a function call syntax rather37than a colon to separate filter name and arguments. Additionally the38extension interface in Jinja is fundamentally different from the Django one39which means that your custom tags won't work any longer.40
38 unmodified lines
79So some amount of logic is required in templates to keep everyone happy.80And Jinja leaves it pretty much to you how much logic you want to put into81templates. There are some restrictions in what you can do and what not.8283Jinja2 neither allows you to put arbitrary Python code into templates nor83Jinja neither allows you to put arbitrary Python code into templates nor84does it allow all Python expressions. The operators are limited to the85most common ones and more advanced expressions such as list comprehensions86and generator expressions are not supported. This keeps the template engine87easier to maintain and templates more readable.
17 unmodified lines
105integers and floats for a table of statistics the template designer can106omit the escaping because he knows that integers or floats don't contain107any unsafe parameters.108109Additionally Jinja2 is a general purpose template engine and not only used109Additionally Jinja is a general purpose template engine and not only used110for HTML/XML generation. For example you may generate LaTeX, emails,111CSS, JavaScript, or configuration files.112113Why is the Context immutable?
15 unmodified lines
129--------------------------------------------130131If the debugsupport module is not compiled and you are using a Python132installation without ctypes (Python 2.4 without ctypes, Jython or Google's133AppEngine) Jinja2 is unable to provide correct debugging information and133AppEngine) Jinja is unable to provide correct debugging information and134the traceback may be incomplete. There is currently no good workaround135for Jython or the AppEngine as ctypes is unavailable there and it's not136possible to use the debugsupport extension.137
11 unmodified lines
149150Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151-----------------------------------------------------------152153Python 2.3 is missing a lot of features that are used heavily in Jinja2. This153Python 2.3 is missing a lot of features that are used heavily in Jinja. This154decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155harder to maintain the code for older Python versions. If you really need156Python 2.3 support you either have to use Jinja 1 or other templating157engines that still support 2.3.
1 unmodified line
159Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160Python 2 and 3 by the same sourcecode (without using 2to3). It was required to161drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode162literals in a way compatible to each other version. If you really need support163for older Python 2 (or 3) versions, you can just use Jinja2 2.6.163for older Python 2 (or 3) versions, you can just use Jinja 2.6.164165Python 2.6/3.3 support was dropped because it got dropped in various upstream166projects (such as wheel or pytest), which would make it difficult to continue167supporting it. Jinja2 2.10 was the last version supporting Python 2.6/3.3.167supporting it. Jinja 2.10 was the last version supporting Python 2.6/3.3.168169My Macros are overridden by something170-------------------------------------171
13 unmodified lines
185 {% extends 'layout.tmpl' %}186 {% macro foo() %}CHILD{% endmacro %}187 {% block body %}{{ foo() }}{% endblock %}188189This will print ``LAYOUT`` in Jinja2. This is a side effect of having189This will print ``LAYOUT`` in Jinja. This is a side effect of having190the parent template evaluated after the child one. This allows child191templates passing information to the parent template. To avoid this192issue rename the macro or variable in the parent template to have an193uncommon prefix.
2 unmodified lines
modified:docs/integration.rst+6 added-6 removed
1Integration2===========34Jinja2 provides some code for integration into other tools such as frameworks,4Jinja provides some code for integration into other tools such as frameworks,5the `Babel`_ library or your favourite editor for fancy code highlighting.6This is a brief description of whats included.78Files to help integration are available
9 unmodified lines
18support is implemented as part of the :ref:`i18n-extension` extension.1920Gettext messages extracted from both `trans` tags and code expressions.2122To extract gettext messages from templates, the project needs a Jinja2 section22To extract gettext messages from templates, the project needs a Jinja section23in its Babel extraction method `mapping file`_:2425.. sourcecode:: ini26
31 unmodified lines
58With `Pylons`_ 0.9.7 onwards it's incredible easy to integrate Jinja into a59Pylons powered application.6061The template engine is configured in `config/environment.py`. The configuration62for Jinja2 looks something like that::62for Jinja looks something like that::6364 from jinja2 import Environment, PackageLoader65 config['pylons.app_globals'].jinja_env = Environment(66 loader=PackageLoader('yourapplication', 'templates')
13 unmodified lines
8081TextMate82--------8384There is a `bundle for TextMate`_ that supports syntax highlighting for Jinja185and Jinja2 for text based templates as well as HTML. It also contains a few84There is a `bundle for TextMate`_ that supports syntax highlighting for Jinja 185and Jinja 2 for text based templates as well as HTML. It also contains a few86often used snippets.8788.. _bundle for TextMate: https://github.com/mitsuhiko/jinja2-tmbundle89
1 unmodified line
91---9293A syntax plugin for `Vim`_ is available `from the jinja repository94<https://github.com/pallets/jinja/blob/master/ext/Vim/jinja.vim>`_. The script95supports Jinja1 and Jinja2. Once installed, two file types are available95supports Jinja 1 and Jinja 2. Once installed, two file types are available96(``jinja`` and ``htmljinja``). The first one is for text-based templates and the97second is for HTML templates. For HTML documents, the plugin attempts to98automatically detect Jinja syntax inside of existing HTML documents.99
7 unmodified lines
modified:docs/intro.rst+13 added-13 removed
1Introduction2============34This is the documentation for the Jinja2 general purpose templating language.5Jinja2 is a library for Python that is designed to be flexible, fast and secure.4This is the documentation for the Jinja general purpose templating language.5Jinja is a library for Python that is designed to be flexible, fast and secure.67If you have any exposure to other text-based template languages, such as Smarty or8Django, you should feel right at home with Jinja2. It's both designer and8Django, you should feel right at home with Jinja. It's both designer and9developer friendly by sticking to Python's principles and adding functionality10useful for templating environments.1112Prerequisites13-------------1415Jinja2 works with Python 2.7.x and >= 3.4. If you are using Python163.2 you can use an older release of Jinja2 (2.6) as support for Python 3.217was dropped in Jinja2 version 2.7. The last release which supported Python 2.618and 3.3 was Jinja2 2.10.15Jinja works with Python 2.7.x and >= 3.5. If you are using Python163.2 you can use an older release of Jinja (2.6) as support for Python 3.217was dropped in Jinja version 2.7. The last release which supported Python 2.618and 3.3 was Jinja 2.10.1920If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21need `setuptools`_ or `distribute`_ installed at runtime.2223Installation24------------2526You can install the most recent Jinja2 version using `pip`_::26You can install the most recent Jinja version using `pip`_::2728 pip install Jinja22930This will install Jinja2 in your Python installation's site-packages directory.30This will install Jinja in your Python installation's site-packages directory.3132Installing the development version33~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~34
14 unmodified lines
4950MarkupSafe Dependency51~~~~~~~~~~~~~~~~~~~~~5253As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you install54Jinja2 via ``pip`` it will be installed automatically for you.53As of version 2.7 Jinja depends on the `MarkupSafe`_ module. If you install54Jinja via ``pip`` it will be installed automatically for you.5556.. _MarkupSafe: https://markupsafe.palletsprojects.com/5758Basic API Usage59---------------6061This section gives you a brief introduction to the Python API for Jinja261This section gives you a brief introduction to the Python API for Jinja62templates.6364The most basic way to create a template and render it is through65:class:`~jinja2.Template`. This however is not the recommended way to
10 unmodified lines
76called with a dict or keyword arguments expands the template. The dict77or keywords arguments passed to the template are the so-called "context"78of the template.7980What you can see here is that Jinja2 is using unicode internally and the80What you can see here is that Jinja is using unicode internally and the81return value is an unicode string. So make sure that your application is82indeed using unicode internally.
modified:docs/sandbox.rst+5 added-5 removed
1Sandbox2=======34The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe4The Jinja sandbox can be used to evaluate untrusted code. Access to unsafe5attributes and methods is prohibited.67Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8the following piece of code shows how it works:
26 unmodified lines
35.. autofunction:: modifies_known_mutable3637.. admonition:: Note3839 The Jinja2 sandbox alone is no solution for perfect security. Especially39 The Jinja sandbox alone is no solution for perfect security. Especially40 for web applications you have to keep in mind that users may create41 templates with arbitrary HTML in so it's crucial to ensure that (if you42 are running multiple users on the same server) they can't harm each other43 via JavaScript insertions and much more.
9 unmodified lines
53---------------------5455.. versionadded:: 2.65657For maximum performance Jinja2 will let operators call directly the type57For maximum performance Jinja will let operators call directly the type58specific callback methods. This means that it's not possible to have this59intercepted by overriding :meth:`Environment.call`. Furthermore a60conversion from operator to special method is not always directly possible61due to how operators work. For instance for divisions more than one
2 unmodified lines
64With Jinja 2.6 there is now support for explicit operator intercepting.65This can be used to customize specific operators as necessary. In order66to intercept an operator one has to override the67:attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the68operator that needs to be intercepted is added to that set Jinja2 will68operator that needs to be intercepted is added to that set Jinja will69generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop`70function. For unary operators the `unary` attributes and methods have to71be used instead.72
16 unmodified lines
89 return SandboxedEnvironment.call_binop(self, context,90 operator, left, right)9192Make sure to always call into the super method, even if you are not93intercepting the call. Jinja2 might internally call the method to93intercepting the call. Jinja might internally call the method to94evaluate expressions.
modified:docs/switching.rst+31 added-31 removed
2 unmodified lines
34.. highlight:: html+jinja56If you have used a different template engine in the past and want to switch7to Jinja2 here is a small guide that shows the basic syntactic and semantic7to Jinja here is a small guide that shows the basic syntactic and semantic8changes between some common, similar text template engines for Python.910Jinja111------10Jinja 111-------1213Jinja2 is mostly compatible with Jinja1 in terms of API usage and template14syntax. The differences between Jinja1 and 2 are explained in the following13Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template14syntax. The differences between Jinja 1 and 2 are explained in the following15list.1617API18~~~1920Loaders21 Jinja2 uses a different loader API. Because the internal representation21 Jinja 2 uses a different loader API. Because the internal representation22 of templates changed there is no longer support for external caching23 systems such as memcached. The memory consumed by templates is comparable24 with regular Python modules now and external caching doesn't give any25 advantage. If you have used a custom loader in the past have a look at26 the new :ref:`loader API <loaders>`.2728Loading templates from strings29 In the past it was possible to generate templates from a string with the30 default environment configuration by using `jinja.from_string`. Jinja230 default environment configuration by using `jinja.from_string`. Jinja 231 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.3334Automatic unicode conversion35 Jinja1 performed automatic conversion of bytestrings in a given encoding35 Jinja 1 performed automatic conversion of bytestrings in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python ASCII38 bytestring to Unicode conversion. An application powered by Jinja239 *has to* use unicode internally everywhere or make sure that Jinja2 only38 bytestring to Unicode conversion. An application powered by Jinja 239 *has to* use unicode internally everywhere or make sure that Jinja 2 only40 gets unicode strings passed.4142i18n43 Jinja1 used custom translators for internationalization. i18n is now44 available as Jinja2 extension and uses a simpler, more gettext friendly43 Jinja 1 used custom translators for internationalization. i18n is now44 available as Jinja 2 extension and uses a simpler, more gettext friendly45 interface and has support for babel. For more details see46 :ref:`i18n-extension`.4748Internal methods49 Jinja1 exposed a few internal methods on the environment object such49 Jinja 1 exposed a few internal methods on the environment object such50 as `call_function`, `get_attribute` and others. While they were marked51 as being an internal method it was possible to override them. Jinja251 as being an internal method it was possible to override them. Jinja 252 doesn't have equivalent methods.5354Sandbox55 Jinja1 was running sandbox mode by default. Few applications actually56 used that feature so it became optional in Jinja2. For more details55 Jinja 1 was running sandbox mode by default. Few applications actually56 used that feature so it became optional in Jinja 2. For more details57 about the sandboxed execution see :class:`SandboxedEnvironment`.5859Context60 Jinja1 had a stacked context as storage for variables passed to the61 environment. In Jinja2 a similar object exists but it doesn't allow60 Jinja 1 had a stacked context as storage for variables passed to the61 environment. In Jinja 2 a similar object exists but it doesn't allow62 modifications nor is it a singleton. As inheritance is dynamic now63 multiple context objects may exist during template evaluation.6465Filters and Tests
3 unmodified lines
6970Templates71~~~~~~~~~7273Jinja2 has mostly the same syntax as Jinja1. What's different is that73Jinja 2 has mostly the same syntax as Jinja 1. What's different is that74macros require parentheses around the argument list now.7576Additionally Jinja2 allows dynamic inheritance now and dynamic includes.76Additionally Jinja 2 allows dynamic inheritance now and dynamic includes.77The old helper function `rendertemplate` is gone now, `include` can be used78instead. Includes no longer import macros and variable assignments, for79that the new `import` tag is used. This concept is explained in the80:ref:`import` documentation.
6 unmodified lines
87Django88------8990If you have previously worked with Django templates, you should find91Jinja2 very familiar. In fact, most of the syntax elements look and91Jinja very familiar. In fact, most of the syntax elements look and92work the same.9394However, Jinja2 provides some more syntax elements covered in the94However, Jinja provides some more syntax elements covered in the95documentation and some work a bit different.9697This section covers the template changes. As the API is fundamentally98different we won't cover it here.
19 unmodified lines
118119Filter Arguments120~~~~~~~~~~~~~~~~121122Jinja2 provides more than one argument for filters. Also the syntax for122Jinja provides more than one argument for filters. Also the syntax for123argument passing is different. A template that looks like this in Django::124125 {{ items|join:", " }}126
18 unmodified lines
145146Loops147~~~~~148149For loops work very similarly to Django, but notably the Jinja2 special149For loops work very similarly to Django, but notably the Jinja special150variable for the loop context is called `loop`, not `forloop` as in Django.151152In addition, the Django `empty` argument is called `else` in Jinja2. For152In addition, the Django `empty` argument is called `else` in Jinja. For153example, the Django template::154155 {% for item in items %}156 {{ item }}
34 unmodified lines
191----192193.. highlight:: html+mako194195If you have used Mako so far and want to switch to Jinja2 you can configure196Jinja2 to look more like Mako:195If you have used Mako so far and want to switch to Jinja you can configure196Jinja to look more like Mako:197198.. sourcecode:: python199200 env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')201202With an environment configured like that, Jinja2 should be able to interpret203a small subset of Mako templates. Jinja2 does not support embedded Python202With an environment configured like that, Jinja should be able to interpret203a small subset of Mako templates. Jinja does not support embedded Python204code, so you would have to move that out of the template. The syntax for defs205(which are called macros in Jinja2) and template inheritance is different too.205(which are called macros in Jinja) and template inheritance is different too.206The following Mako template::207208 <%inherit file="layout.html" />209 <%def name="title()">Page Title</%def>
2 unmodified lines
212 <li>${item}</li>213 % endfor214 </ul>215216Looks like this in Jinja2 with the above configuration::216Looks like this in Jinja with the above configuration::217218 <% extends "layout.html" %>219 <% block title %>Page Title<% endblock %>220 <% block body %>
6 unmodified lines
modified:docs/templates.rst+9 added-9 removed
103 unmodified lines
104.. _notes-on-subscriptions:105106.. admonition:: Implementation107108 For the sake of convenience, ``foo.bar`` in Jinja2 does the following108 For the sake of convenience, ``foo.bar`` in Jinja does the following109 things on the Python layer:110111 - check for an attribute called `bar` on `foo`112 (``getattr(foo, 'bar')``)
131 unmodified lines
244245If :ref:`line-statements` are enabled, they strip leading whitespace246automatically up to the beginning of the line.247248By default, Jinja2 also removes trailing newlines. To keep single248By default, Jinja also removes trailing newlines. To keep single249trailing newlines, configure Jinja to `keep_trailing_newline`.250251.. admonition:: Note252
239 unmodified lines
492493Named Block End-Tags494~~~~~~~~~~~~~~~~~~~~495496Jinja2 allows you to put the name of the block after the end tag for better496Jinja allows you to put the name of the block after the end tag for better497readability::498499 {% block sidebar %}500 {% block inner_sidebar %}
97 unmodified lines
598still take place and result in double-escaped characters. If you know599you have data that is already safe but not marked, be sure to wrap it in600``Markup`` or use the ``|safe`` filter.601602Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template602Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template603data that is marked as safe.604605String literals in templates with automatic escaping are considered unsafe606because native Python strings (``str``, ``unicode``, ``basestring``) are not
139 unmodified lines
746writing `{% set outer_loop = loop %}` after the loop that we want to747use recursively. Then, we can call it using `{{ outer_loop(...) }}`748749Please note that assignments in loops will be cleared at the end of the750iteration and cannot outlive the loop scope. Older versions of Jinja2 had750iteration and cannot outlive the loop scope. Older versions of Jinja had751a bug where in some circumstances it appeared that assignments would work.752This is not supported. See :ref:`assignments` for more information about753how to deal with this.754
168 unmodified lines
923924Filters925~~~~~~~926927Filter sections allow you to apply regular Jinja2 filters on a block of927Filter sections allow you to apply regular Jinja filters on a block of928template data. Just wrap the code in the special `filter` section::929930 {% filter upper %}931 This text becomes uppercase
156 unmodified lines
10881089Import1090~~~~~~10911092Jinja2 supports putting often used code into macros. These macros can go into1092Jinja supports putting often used code into macros. These macros can go into1093different templates and get imported from there. This works similarly to the1094import statements in Python. It's important to know that imports are cached1095and imported templates don't have access to the current template variables,1096just the globals by default. For more details about context behavior of
468 unmodified lines
15651566Extensions1567----------15681569The following sections cover the built-in Jinja2 extensions that may be1569The following sections cover the built-in Jinja extensions that may be1570enabled by an application. An application could also provide further1571extensions not covered by this documentation; in which case there should1572be a separate document explaining said :ref:`extensions1573<jinja-extensions>`.
199 unmodified lines
1773behavior of referencing one variable to another had some unintended1774consequences. In particular one variable could refer to another defined1775in the same with block's opening statement. This caused issues with the1776cleaned up scoping behavior and has since been improved. In particular1777in newer Jinja2 versions the following code always refers to the variable1777in newer Jinja versions the following code always refers to the variable1778`a` from outside the `with` block::17791780 {% with a={}, b=a.attribute %}...{% endwith %}1781
39 unmodified lines
modified:docs/tricks.rst+2 added-2 removed
1 unmodified line
2===============34.. highlight:: html+jinja56This part of the documentation shows some tips and tricks for Jinja26This part of the documentation shows some tips and tricks for Jinja7templates.8910.. _null-master-fallback:1112Null-Master Fallback13--------------------1415Jinja2 supports dynamic inheritance and does not distinguish between parent15Jinja supports dynamic inheritance and does not distinguish between parent16and child template as long as no `extends` tag is visited. While this leads17to the surprising behavior that everything before the first `extends` tag18including whitespace is printed out instead of being ignored, it can be used19for a neat trick.
81 unmodified lines
modified:examples/rwbench/django/layout.html+1 added-1 removed
7 unmodified lines
8 <div class="contents">9 <div class="header">10 <h1>RealWorld Benchmark</h1>11 <blockquote><p>12 A less stupid benchmark for Mako and Jinja2 to get an impression how12 A less stupid benchmark for Mako and Jinja to get an impression how13 code changes affect runtime performance.14 </p></blockquote>15 </div>16 <ul class="navigation">
13 unmodified lines
modified:examples/rwbench/genshi/layout.html+1 added-1 removed
9 unmodified lines
10 <div class="contents">11 <div class="header">12 <h1>RealWorld Benchmark</h1>13 <blockquote><p>14 A less stupid benchmark for Mako and Jinja2 to get an impression how14 A less stupid benchmark for Mako and Jinja to get an impression how15 code changes affect runtime performance.16 </p></blockquote>17 </div>18 <ul class="navigation">
12 unmodified lines
modified:examples/rwbench/jinja/layout.html+1 added-1 removed
7 unmodified lines
8 <div class="contents">9 <div class="header">10 <h1>RealWorld Benchmark</h1>11 <blockquote><p>12 A less stupid benchmark for Mako and Jinja2 to get an impression how12 A less stupid benchmark for Mako and Jinja to get an impression how13 code changes affect runtime performance.14 </p></blockquote>15 </div>16 <ul class="navigation">
13 unmodified lines
modified:examples/rwbench/mako/layout.html+1 added-1 removed
7 unmodified lines
8 <div class="contents">9 <div class="header">10 <h1>RealWorld Benchmark</h1>11 <blockquote><p>12 A less stupid benchmark for Mako and Jinja2 to get an impression how12 A less stupid benchmark for Mako and Jinja to get an impression how13 code changes affect runtime performance.14 </p></blockquote>15 </div>16 <ul class="navigation">
14 unmodified lines
modified:examples/rwbench/rwbench.py+2 added-2 removed
1 unmodified line
2"""3 RealWorldish Benchmark4 ~~~~~~~~~~~~~~~~~~~~~~56 A more real-world benchmark of Jinja2. Like the other benchmark in the7 Jinja2 repository this has no real-world usefulnes (despite the name).6 A more real-world benchmark of Jinja. Like the other benchmark in the7 Jinja repository this has no real-world usefulnes (despite the name).8 Just go away and ignore it. NOW!910 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.
101 unmodified lines
modified:examples/bench.py+2 added-2 removed
1"""\2 This benchmark compares some python templating engines with Jinja 2 so3 that we get a picture of how fast Jinja 2 is for a semi real world2 This benchmark compares some python templating engines with Jinja so3 that we get a picture of how fast Jinja is for a semi real world4 template. If a template engine is not installed the test is skipped.\5"""6import sys7import cgi
426 unmodified lines
modified:ext/django2jinja/django2jinja.py+1 added-1 removed
1 unmodified line
2"""3 Django to Jinja4 ~~~~~~~~~~~~~~~56 Helper module that can convert django templates into Jinja2 templates.6 Helper module that can convert django templates into Jinja templates.78 This file is not intended to be used as stand alone application but to9 be used as library. To convert templates you basically create your own10 writer, add extra conversion logic for your custom template tags,
758 unmodified lines
modified:ext/Vim/jinja.vim+1 added-1 removed
8 unmodified lines
9" appear wrong in the template.10"11" Changes:12"13" 2008 May 9: Added support for Jinja2 changes (new keyword rules)13" 2008 May 9: Added support for Jinja 2 changes (new keyword rules)1415" .vimrc variable to disable html highlighting16if !exists('g:jinja_syntax_html')17 let g:jinja_syntax_html=1
121 unmodified lines
modified:ext/djangojinja2.py+5 added-5 removed
1 unmodified line
2"""3 djangojinja24 ~~~~~~~~~~~~56 Adds support for Jinja2 to Django.6 Adds support for Jinja to Django.78 Configuration variables:910 ======================= =============================================11 Key Description12 ======================= =============================================13 `JINJA2_TEMPLATE_DIRS` List of template folders14 `JINJA2_EXTENSIONS` List of Jinja2 extensions to use15 `JINJA2_CACHE_SIZE` The size of the Jinja2 template cache.14 `JINJA2_EXTENSIONS` List of Jinja extensions to use15 `JINJA2_CACHE_SIZE` The size of the Jinja template cache.16 ======================= =============================================1718 :copyright: (c) 2009 by the Jinja Team.19 :license: BSD.
12 unmodified lines
32_jinja_env = None333435def get_env():36 """Get the Jinja2 env and initialize it if necessary."""36 """Get the Jinja env and initialize it if necessary."""37 global _jinja_env38 if _jinja_env is None:39 _jinja_env = create_env()40 return _jinja_env414243def create_env():44 """Create a new Jinja2 environment."""44 """Create a new Jinja environment."""45 searchpath = list(settings.JINJA2_TEMPLATE_DIRS)46 return Environment(loader=FileSystemLoader(searchpath),47 auto_reload=settings.TEMPLATE_DEBUG,48 cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 400),
38 unmodified lines
modified:ext/inlinegettext.py+1 added-1 removed
1 unmodified line
2"""3 Inline Gettext4 ~~~~~~~~~~~~~~56 An example extension for Jinja2 that supports inline gettext calls.6 An example extension for Jinja that supports inline gettext calls.7 Requires the i18n extension to be loaded.89 :copyright: (c) 2009 by the Jinja Team.10 :license: BSD.
68 unmodified lines
modified:jinja2/__init__.py+2 added-2 removed
1 unmodified line
2"""3 jinja24 ~~~~~~56 Jinja2 is a template engine written in pure Python. It provides a6 Jinja is a template engine written in pure Python. It provides a7 Django inspired non-XML syntax but supports inline expressions and8 an optional sandboxed environment.910 Nutshell11 --------1213 Here a small example of a Jinja2 template::13 Here a small example of a Jinja template::1415 {% extends 'base.html' %}16 {% block title %}Memberlist{% endblock %}17 {% block content %}
55 unmodified lines
modified:jinja2/bccache.py+2 added-2 removed
138 unmodified lines
139 with open(filename, 'wb') as f:140 bucket.write_bytecode(f)141142 A more advanced version of a filesystem based bytecode cache is part of143 Jinja2.143 Jinja.144 """145146 def load_bytecode(self, bucket):147 """Subclasses have to override this method to load bytecode into a
9 unmodified lines
157 """158 raise NotImplementedError()159160 def clear(self):161 """Clears the cache. This method is not used by Jinja2 but should be161 """Clears the cache. This method is not used by Jinja but should be162 implemented to allow applications to clear the bytecode cache used163 by a particular environment.164 """165
196 unmodified lines
modified:jinja2/environment.py+1 added-1 removed
483 unmodified lines
484 tree of nodes is used by the compiler to convert the template into485 executable source- or bytecode. This is useful for debugging or to486 extract information from templates.487488 If you are :ref:`developing Jinja2 extensions <writing-extensions>`488 If you are :ref:`developing Jinja extensions <writing-extensions>`489 this gives you a good overview of the node tree generated.490 """491 try:492 return self._parse(source, name, filename)
786 unmodified lines
modified:jinja2/ext.py+3 added-3 removed
98 unmodified lines
99 to filter tokens returned. This method has to return an iterable of100 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a101 :class:`~jinja2.lexer.TokenStream`.102103 In the `ext` folder of the Jinja2 source distribution there is a file103 In the `ext` folder of the Jinja source distribution there is a file104 called `inlinegettext.py` which implements a filter that utilizes this105 method.106 """107 return stream
59 unmodified lines
167 return ngettext168169170class InternationalizationExtension(Extension):171 """This extension adds gettext support to Jinja2."""171 """This extension adds gettext support to Jinja."""172 tags = {'trans'}173174 # TODO: the i18n extension is currently reevaluating values in a few175 # situations. Take this example:
239 unmodified lines
415 return nodes.Output([node])416417418class ExprStmtExtension(Extension):419 """Adds a `do` tag to Jinja2 that works like the print statement just419 """Adds a `do` tag to Jinja that works like the print statement just420 that it doesn't print the return value.421 """422 tags = set(['do'])423
259 unmodified lines
modified:jinja2/filters.py+1 added-1 removed
666 unmodified lines
667 -> "foo bar baz qux"668 {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}669 -> "foo bar..."670671 The default leeway on newer Jinja2 versions is 5 and was 0 before but671 The default leeway on newer Jinja versions is 5 and was 0 before but672 can be reconfigured globally.673 """674 if leeway is None:675 leeway = env.policies['truncate.leeway']
642 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
103 unmodified lines
104 return ctx105106107class Node(with_metaclass(NodeType, object)):108 """Baseclass for all Jinja2 nodes. There are a number of nodes available108 """Baseclass for all Jinja nodes. There are a number of nodes available109 of different types. There are four major types:110111 - :class:`Stmt`: statements112 - :class:`Expr`: expressions
892 unmodified lines
modified:jinja2/parser.py+2 added-2 removed
28 unmodified lines
29}303132class Parser(object):33 """This is the central parsing class Jinja2 uses. It's passed to33 """This is the central parsing class Jinja uses. It's passed to34 extensions and can be used to parse expressions or statements.35 """3637 def __init__(self, environment, source, name=None, filename=None,
356 unmodified lines
394 return node395396 def parse_assign_target(self, with_tuple=True, name_only=False,397 extra_end_rules=None, with_namespace=False):398 """Parse an assignment target. As Jinja2 allows assignments to398 """Parse an assignment target. As Jinja allows assignments to399 tuples, this function can parse all allowed assignment targets. Per400 default assignments to tuples are parsed, that can be disable however401 by setting `with_tuple` to `False`. If only assignments to names are402 wanted `name_only` can be set to `True`. The `extra_end_rules`
505 unmodified lines
modified:jinja2/tests.py+2 added-2 removed
85 unmodified lines
86 """87 return value is True888990# NOTE: The existing Jinja2 'number' test matches booleans and floats90# NOTE: The existing 'number' test matches booleans and floats91def test_integer(value):92 """Return true if the object is an integer.9394 .. versionadded:: 2.1195 """96 return isinstance(value, integer_types) and value is not True and value is not False979899# NOTE: The existing Jinja2 'number' test matches booleans and integers99# NOTE: The existing 'number' test matches booleans and integers100def test_float(value):101 """Return true if the object is a float.102103 .. versionadded:: 2.11
118 unmodified lines
modified:jinja2/utils.py+2 added-2 removed
108 unmodified lines
109 pass110111112def clear_caches():113 """Jinja2 keeps internal caches for environments and lexers. These are114 used so that Jinja2 doesn't have to recreate environments and lexers all113 """Jinja keeps internal caches for environments and lexers. These are114 used so that Jinja doesn't have to recreate environments and lexers all115 the time. Normally you don't have to care about that but if you are116 measuring memory consumption you may want to clean the caches.117 """118 from jinja2.environment import _spontaneous_environments
551 unmodified lines
modified:scripts/jinja2-debug.py+3 added-3 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4 Jinja2 Debug Interface5 ~~~~~~~~~~~~~~~~~~~~~~4 Jinja Debug Interface5 ~~~~~~~~~~~~~~~~~~~~~67 Helper script for internal Jinja2 debugging. Requires Werkzeug.7 Helper script for internal Jinja debugging. Requires Werkzeug.89 :copyright: Copyright 2010 by Armin Ronacher.10 :license: BSD.11"""
32 unmodified lines
modified:CHANGES.rst+9 added-9 removed
256 unmodified lines
257 case the string is barely truncated at all.258- Change the logic for macro autoescaping to be based on the runtime259 autoescaping information at call time instead of macro define time.260- Ported a modified version of the ``tojson`` filter from Flask to261 Jinja2 and hooked it up with the new policy framework.261 Jinja and hooked it up with the new policy framework.262- Block sets are now marked ``safe`` by default.263- On Python 2 the asciification of ASCII strings can now be disabled264 with the ``compiler.ascii_str`` policy.265- Tests now no longer accept an arbitrary expression as first argument
37 unmodified lines
303- Added equalto filter that helps with select filters.304- Changed cache keys to use absolute file names if available instead305 of load names.306- Fixed loop length calculation for some iterators.307- Changed how Jinja2 enforces strings to be native strings in Python 2307- Changed how Jinja enforces strings to be native strings in Python 2308 to work when people break their default encoding.309- Added :func:`make_logging_undefined` which returns an undefined310 object that logs failures into a logger.311- If unmarshalling of cached data fails the template will be reloaded
112 unmodified lines
424- Scoped blocks now properly treat toplevel assignments and imports.425 Previously an import suddenly "disappeared" in a scoped block.426- Automatically detect newer Python interpreter versions before427 loading code from bytecode caches to prevent segfaults on invalid428 opcodes. The segfault in earlier Jinja2 versions here was not a429 Jinja2 bug but a limitation in the underlying Python interpreter. If430 you notice Jinja2 segfaulting in earlier versions after an upgrade428 opcodes. The segfault in earlier Jinja versions here was not a429 Jinja bug but a limitation in the underlying Python interpreter. If430 you notice Jinja segfaulting in earlier versions after an upgrade431 of the Python interpreter you don't have to upgrade, it's enough to432 flush the bytecode cache. This just no longer makes this necessary,433 Jinja2 will automatically detect these cases now.433 Jinja will automatically detect these cases now.434- The sum filter can now sum up values by attribute. This is a435 backwards incompatible change. The argument to the filter previously436 was the optional starting index which defaults to zero. This now437 became the second argument to the function because it's rarely used.
59 unmodified lines
497- Using the variable ``num`` in newstyle gettext for something else498 than the pluralize count will no longer raise a :exc:`KeyError`.499- Removed builtin markup class and switched to markupsafe. For500 backwards compatibility the pure Python implementation still exists501 but is pulled from markupsafe by the Jinja2 developers. The debug501 but is pulled from markupsafe by the Jinja developers. The debug502 support went into a separate feature called "debugsupport" and is503 disabled by default because it is only relevant for Python 2.4504- Fixed an issue with unary operators having the wrong precedence.505
74 unmodified lines
580-------------581582Released 2009-09-14583584- Fixes some smaller problems for Jinja2 on Jython.584- Fixes some smaller problems for Jinja on Jython.585586587Version 2.2588-----------
97 unmodified lines
686--------------687688Released 2008-06-09689690- First release of Jinja2690- First release of Jinja 2.