Merge pull request #1087 from pallets/jinja-name
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use "Jinja" instead of "Jinja2"
authored by David Lord · committed by GitHub · parents 6e50bbd, 57626a0 · 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
Provenance
- Commit
1af1205- Tree
a0aeddd- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
6e50bbd- Parent 2
57626a0
30 files changed+158 added−160 removed
modified:docs/api.rst+28 added-30 removed
1 unmodified line2 ===3 4 .. module:: jinja25 :noindex:6- :synopsis: public Jinja2 API6+ :synopsis: public Jinja API7 8-This document describes the API to Jinja2 and not the template language. It8+This document describes the API to Jinja and not the template language. It9 will be most useful as reference to those implementing the template interface10-to the application and not those who are creating Jinja2 templates.10+to the application and not those who are creating Jinja templates.11 12 Basics13 ------14 15-Jinja2 uses a central object called the template :class:`Environment`.15+Jinja uses a central object called the template :class:`Environment`.16 Instances of this class are used to store the configuration and global objects,17 and are used to load templates from the file system or other locations.18 Even if you are creating templates from strings by using the constructor of19 :class:`Template` class, an environment is created automatically for you,3 unmodified lines23 initialization and use that to load templates. In some cases however, it's24 useful to have multiple environments side by side, if different configurations25 are in use.26 27-The simplest way to configure Jinja2 to load templates for your application27+The simplest way to configure Jinja to load templates for your application28 looks roughly like this::29 30 from jinja2 import Environment, PackageLoader, select_autoescape31 env = Environment(22 unmodified lines54 a lot easier to use it also enables template inheritance.55 56 .. admonition:: Notes on Autoescaping57 58- 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.61 62 63 Unicode64 -------65 66-Jinja2 is using Unicode internally which means that you have to pass Unicode66+Jinja is using Unicode internally which means that you have to pass Unicode67 objects to the render function or bytestrings that only consist of ASCII68 characters. Additionally newlines are normalized to one end of line69 sequence which is per default UNIX style (``\n``).70 16 unmodified lines87 # -*- coding: utf-8 -*-88 89 We recommend utf-8 as Encoding for Python modules and templates as it's90 possible to represent every Unicode character in utf-8 and because it's91-backwards compatible to ASCII. For Jinja2 the default encoding of templates91+backwards compatible to ASCII. For Jinja the default encoding of templates92 is assumed to be utf-8.93 94-It is not possible to use Jinja2 to process non-Unicode data. The reason95-for this is that Jinja2 uses Unicode already on the language level. For96-example Jinja2 treats the non-breaking space as valid whitespace inside94+It is not possible to use Jinja to process non-Unicode data. The reason95+for this is that Jinja uses Unicode already on the language level. For96+example Jinja treats the non-breaking space as valid whitespace inside97 expressions which requires knowledge of the encoding or operating on an98 Unicode string.99 100 For more details about Unicode in Python have a look at the excellent101 `Unicode documentation`_.102 103-Another important thing is how Jinja2 is handling string literals in103+Another important thing is how Jinja is handling string literals in104 templates. A naive implementation would be using Unicode strings for105 all string literals but it turned out in the past that this is problematic106 as some libraries are typechecking against `str` explicitly. For example107 `datetime.strftime` does not accept Unicode arguments. To not break it108-completely Jinja2 is returning `str` for strings that fit into ASCII and108+completely Jinja is returning `str` for strings that fit into ASCII and109 for everything else `unicode`:110 111 >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module112 >>> m.a7 unmodified lines120 High Level API121 --------------122 123 The high-level API is the API you will use in the application to load and124-render Jinja2 templates. The :ref:`low-level-api` on the other side is only125-useful if you want to dig deeper into Jinja2 or :ref:`develop extensions124+render Jinja templates. The :ref:`low-level-api` on the other side is only125+useful if you want to dig deeper into Jinja or :ref:`develop extensions126 <jinja-extensions>`.127 128 .. autoclass:: Environment([options])129 :members: from_string, get_template, select_template,129 unmodified lines259 ------------260 261 .. versionchanged:: 2.4262 263-Jinja2 now comes with autoescaping support. As of Jinja 2.9 the263+Jinja now comes with autoescaping support. As of Jinja 2.9 the264 autoescape extension is removed and built-in. However autoescaping is265 not yet enabled by default though this will most likely change in the266 future. It's recommended to configure a sensible default for267 autoescaping. This makes it possible to enable and disable autoescaping31 unmodified lines299 300 Notes on Identifiers301 --------------------302 303-Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to304-match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters305-are currently not allowed. This limitation will probably go away as soon as306-unicode identifiers are fully specified for Python 3.303+Jinja uses Python naming rules. Valid identifiers can be any combination304+of Unicode characters accepted by Python.305 306 Filters and tests are looked up in separate namespaces and have slightly307 modified identifier syntax. Filters and tests may contain dots to group308 filters and tests by topic. For example it's perfectly valid to add a133 unmodified lines442 443 .. admonition:: Implementation444 445 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.449 452- 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.453 454 11 unmodified lines466 467 .. autoclass:: jinja2.BaseLoader468 :members: get_source, load469 472-Here a list of the builtin loaders Jinja2 provides:470+Here a list of the builtin loaders Jinja provides:471 472 .. autoclass:: jinja2.FileSystemLoader473 474 .. autoclass:: jinja2.PackageLoader53 unmodified lines528 529 Async Support530 -------------531 534-Starting with version 2.9, Jinja2 also supports the Python `async` and532+Starting with version 2.9, Jinja also supports the Python `async` and533 `await` constructs. As far as template designers go this feature is534 entirely opaque to them however as a developer you should be aware of how535 it's implemented as it influences what type of APIs you can safely expose536 to the template environment.38 unmodified lines575 576 env.policies['urlize.rel'] = 'nofollow noopener'577 578 ``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 lines623 Utilities624 ---------625 626 These helper functions and classes are useful if you add custom filters or629-functions to a Jinja2 environment.627+functions to a Jinja environment.628 629 .. autofunction:: jinja2.environmentfilter630 631 .. autofunction:: jinja2.contextfilter23 unmodified lines655 :members: escape, unescape, striptags656 657 .. admonition:: Note658 661- 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.662 663 248 unmodified lines912 available, otherwise `True`.913 914 .. admonition:: Note915 918- 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`.920 921 The Meta API922 ------------11 unmodified linesmodified:docs/extensions.rst+8 added-8 removed
1 unmodified line2 3 Extensions4 ==========5 6-Jinja2 supports extensions that can add extra filters, tests, globals or even6+Jinja supports extensions that can add extra filters, tests, globals or even7 extend the parser. The main motivation of extensions is to move often used8 code into a reusable class like adding support for internationalization.9 10 11 Adding Extensions12 -----------------13 14-Extensions are added to the Jinja2 environment at creation time. Once the14+Extensions are added to the Jinja environment at creation time. Once the15 environment is created additional extensions cannot be added. To add an16 extension pass a list of extension classes or import paths to the17 ``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following18-example creates a Jinja2 environment with the i18n extension loaded::18+example creates a Jinja environment with the i18n extension loaded::19 20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])21 22 172 unmodified lines195 196 **Import name:** ``jinja2.ext.loopcontrols``197 198 This extension adds support for ``break`` and ``continue`` in loops. After199-enabling, Jinja2 provides those two keywords which work exactly like in199+enabling, Jinja provides those two keywords which work exactly like in200 Python.201 202 .. _with-extension:203 37 unmodified lines241 ------------------242 243 .. module:: jinja2.ext244 245-By writing extensions you can add custom tags to Jinja2. This is a non-trivial245+By writing extensions you can add custom tags to Jinja. This is a non-trivial246 task and usually not needed as the default tags and expressions cover all247 common use cases. The i18n extension is a good example of why extensions are248 useful. Another one would be fragment caching.249 250 When writing extensions you have to keep in mind that you are working with the251-Jinja2 template compiler which does not validate the node tree you are passing251+Jinja template compiler which does not validate the node tree you are passing252 to it. If the AST is malformed you will get all kinds of compiler or runtime253 errors that are horrible to debug. Always make sure you are using the nodes254 you create correctly. The API documentation below shows which nodes exist and255 how to use them.256 257 Example Extension258 ~~~~~~~~~~~~~~~~~259 260-The following example implements a ``cache`` tag for Jinja2 by using the260+The following example implements a ``cache`` tag for Jinja by using the261 `cachelib`_ library:262 263 .. literalinclude:: cache_extension.py264 :language: python99 unmodified lines364 code objects. Extensions that provide custom statements can return nodes to365 execute custom Python code.366 367 The list below describes all nodes that are currently available. The AST may368-change between Jinja2 versions but will stay backwards compatible.368+change between Jinja versions but will stay backwards compatible.369 370 For more information have a look at the repr of :meth:`jinja2.Environment.parse`.371 372 .. module:: jinja2.nodes4 unmodified linesmodified:docs/faq.rst+12 added-12 removed
16 unmodified lines17 18 We really hate benchmarks especially since they don't reflect much. The19 performance of a template depends on many factors and you would have to20 benchmark different engines in different situations. The benchmarks from the21-testsuite show that Jinja2 has a similar performance to `Mako`_ and is between21+testsuite show that Jinja has a similar performance to `Mako`_ and is between22 10 and 20 times faster than Django's template engine or Genshi. These numbers23 should be taken with tons of salt as the benchmarks that took these numbers24 only test a few performance related situations such as looping. Generally25 speaking the performance of a template engine doesn't matter much as the1 unmodified line27 code.28 29 .. _Mako: https://www.makotemplates.org/30 31-How Compatible is Jinja2 with Django?32--------------------------------------31+How Compatible is Jinja with Django?32+------------------------------------33 34-The default syntax of Jinja2 matches Django syntax in many ways. However34+The default syntax of Jinja matches Django syntax in many ways. However35 this similarity doesn't mean that you can use a Django template unmodified36-in Jinja2. For example filter arguments use a function call syntax rather36+in Jinja. For example filter arguments use a function call syntax rather37 than a colon to separate filter name and arguments. Additionally the38 extension interface in Jinja is fundamentally different from the Django one39 which means that your custom tags won't work any longer.40 38 unmodified lines79 So some amount of logic is required in templates to keep everyone happy.80 And Jinja leaves it pretty much to you how much logic you want to put into81 templates. There are some restrictions in what you can do and what not.82 83-Jinja2 neither allows you to put arbitrary Python code into templates nor83+Jinja neither allows you to put arbitrary Python code into templates nor84 does it allow all Python expressions. The operators are limited to the85 most common ones and more advanced expressions such as list comprehensions86 and generator expressions are not supported. This keeps the template engine87 easier to maintain and templates more readable.17 unmodified lines105 integers and floats for a table of statistics the template designer can106 omit the escaping because he knows that integers or floats don't contain107 any unsafe parameters.108 109-Additionally Jinja2 is a general purpose template engine and not only used109+Additionally Jinja is a general purpose template engine and not only used110 for HTML/XML generation. For example you may generate LaTeX, emails,111 CSS, JavaScript, or configuration files.112 113 Why is the Context immutable?15 unmodified lines129 --------------------------------------------130 131 If the debugsupport module is not compiled and you are using a Python132 installation without ctypes (Python 2.4 without ctypes, Jython or Google's133-AppEngine) Jinja2 is unable to provide correct debugging information and133+AppEngine) Jinja is unable to provide correct debugging information and134 the traceback may be incomplete. There is currently no good workaround135 for Jython or the AppEngine as ctypes is unavailable there and it's not136 possible to use the debugsupport extension.137 11 unmodified lines149 150 Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151 -----------------------------------------------------------152 153-Python 2.3 is missing a lot of features that are used heavily in Jinja2. This153+Python 2.3 is missing a lot of features that are used heavily in Jinja. This154 decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155 harder to maintain the code for older Python versions. If you really need156 Python 2.3 support you either have to use Jinja 1 or other templating157 engines that still support 2.3.1 unmodified line159 Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160 Python 2 and 3 by the same sourcecode (without using 2to3). It was required to161 drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode162 literals in a way compatible to each other version. If you really need support163-for older Python 2 (or 3) versions, you can just use Jinja2 2.6.163+for older Python 2 (or 3) versions, you can just use Jinja 2.6.164 165 Python 2.6/3.3 support was dropped because it got dropped in various upstream166 projects (such as wheel or pytest), which would make it difficult to continue167-supporting it. Jinja2 2.10 was the last version supporting Python 2.6/3.3.167+supporting it. Jinja 2.10 was the last version supporting Python 2.6/3.3.168 169 My Macros are overridden by something170 -------------------------------------171 13 unmodified lines185 {% extends 'layout.tmpl' %}186 {% macro foo() %}CHILD{% endmacro %}187 {% block body %}{{ foo() }}{% endblock %}188 189-This will print ``LAYOUT`` in Jinja2. This is a side effect of having189+This will print ``LAYOUT`` in Jinja. This is a side effect of having190 the parent template evaluated after the child one. This allows child191 templates passing information to the parent template. To avoid this192 issue rename the macro or variable in the parent template to have an193 uncommon prefix.2 unmodified linesmodified:docs/integration.rst+6 added-6 removed
1 Integration2 ===========3 4-Jinja2 provides some code for integration into other tools such as frameworks,4+Jinja provides some code for integration into other tools such as frameworks,5 the `Babel`_ library or your favourite editor for fancy code highlighting.6 This is a brief description of whats included.7 8 Files to help integration are available9 unmodified lines18 support is implemented as part of the :ref:`i18n-extension` extension.19 20 Gettext messages extracted from both `trans` tags and code expressions.21 22-To extract gettext messages from templates, the project needs a Jinja2 section22+To extract gettext messages from templates, the project needs a Jinja section23 in its Babel extraction method `mapping file`_:24 25 .. sourcecode:: ini26 31 unmodified lines58 With `Pylons`_ 0.9.7 onwards it's incredible easy to integrate Jinja into a59 Pylons powered application.60 61 The template engine is configured in `config/environment.py`. The configuration62-for Jinja2 looks something like that::62+for Jinja looks something like that::63 64 from jinja2 import Environment, PackageLoader65 config['pylons.app_globals'].jinja_env = Environment(66 loader=PackageLoader('yourapplication', 'templates')13 unmodified lines80 81 TextMate82 --------83 84-There is a `bundle for TextMate`_ that supports syntax highlighting for Jinja185-and Jinja2 for text based templates as well as HTML. It also contains a few84+There is a `bundle for TextMate`_ that supports syntax highlighting for Jinja 185+and Jinja 2 for text based templates as well as HTML. It also contains a few86 often used snippets.87 88 .. _bundle for TextMate: https://github.com/mitsuhiko/jinja2-tmbundle89 1 unmodified line91 ---92 93 A syntax plugin for `Vim`_ is available `from the jinja repository94 <https://github.com/pallets/jinja/blob/master/ext/Vim/jinja.vim>`_. The script95-supports Jinja1 and Jinja2. Once installed, two file types are available95+supports Jinja 1 and Jinja 2. Once installed, two file types are available96 (``jinja`` and ``htmljinja``). The first one is for text-based templates and the97 second is for HTML templates. For HTML documents, the plugin attempts to98 automatically detect Jinja syntax inside of existing HTML documents.99 7 unmodified linesmodified:docs/intro.rst+13 added-13 removed
1 Introduction2 ============3 4-This is the documentation for the Jinja2 general purpose templating language.5-Jinja2 is a library for Python that is designed to be flexible, fast and secure.4+This is the documentation for the Jinja general purpose templating language.5+Jinja is a library for Python that is designed to be flexible, fast and secure.6 7 If you have any exposure to other text-based template languages, such as Smarty or8-Django, you should feel right at home with Jinja2. It's both designer and8+Django, you should feel right at home with Jinja. It's both designer and9 developer friendly by sticking to Python's principles and adding functionality10 useful for templating environments.11 12 Prerequisites13 -------------14 15-Jinja2 works with Python 2.7.x and >= 3.4. If you are using Python16-3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.217-was dropped in Jinja2 version 2.7. The last release which supported Python 2.618-and 3.3 was Jinja2 2.10.15+Jinja works with Python 2.7.x and >= 3.5. If you are using Python16+3.2 you can use an older release of Jinja (2.6) as support for Python 3.217+was dropped in Jinja version 2.7. The last release which supported Python 2.618+and 3.3 was Jinja 2.10.19 20 If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21 need `setuptools`_ or `distribute`_ installed at runtime.22 23 Installation24 ------------25 26-You can install the most recent Jinja2 version using `pip`_::26+You can install the most recent Jinja version using `pip`_::27 28 pip install Jinja229 30-This will install Jinja2 in your Python installation's site-packages directory.30+This will install Jinja in your Python installation's site-packages directory.31 32 Installing the development version33 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~34 14 unmodified lines49 50 MarkupSafe Dependency51 ~~~~~~~~~~~~~~~~~~~~~52 53-As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you install54-Jinja2 via ``pip`` it will be installed automatically for you.53+As of version 2.7 Jinja depends on the `MarkupSafe`_ module. If you install54+Jinja via ``pip`` it will be installed automatically for you.55 56 .. _MarkupSafe: https://markupsafe.palletsprojects.com/57 58 Basic API Usage59 ---------------60 61-This section gives you a brief introduction to the Python API for Jinja261+This section gives you a brief introduction to the Python API for Jinja62 templates.63 64 The most basic way to create a template and render it is through65 :class:`~jinja2.Template`. This however is not the recommended way to10 unmodified lines76 called with a dict or keyword arguments expands the template. The dict77 or keywords arguments passed to the template are the so-called "context"78 of the template.79 80-What you can see here is that Jinja2 is using unicode internally and the80+What you can see here is that Jinja is using unicode internally and the81 return value is an unicode string. So make sure that your application is82 indeed using unicode internally.modified:docs/sandbox.rst+5 added-5 removed
1 Sandbox2 =======3 4-The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe4+The Jinja sandbox can be used to evaluate untrusted code. Access to unsafe5 attributes and methods is prohibited.6 7 Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8 the following piece of code shows how it works:26 unmodified lines35 .. autofunction:: modifies_known_mutable36 37 .. admonition:: Note38 39- 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 lines53 ---------------------54 55 .. versionadded:: 2.656 57-For maximum performance Jinja2 will let operators call directly the type57+For maximum performance Jinja will let operators call directly the type58 specific callback methods. This means that it's not possible to have this59 intercepted by overriding :meth:`Environment.call`. Furthermore a60 conversion from operator to special method is not always directly possible61 due to how operators work. For instance for divisions more than one2 unmodified lines64 With Jinja 2.6 there is now support for explicit operator intercepting.65 This can be used to customize specific operators as necessary. In order66 to intercept an operator one has to override the67 :attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the68-operator that needs to be intercepted is added to that set Jinja2 will68+operator that needs to be intercepted is added to that set Jinja will69 generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop`70 function. For unary operators the `unary` attributes and methods have to71 be used instead.72 16 unmodified lines89 return SandboxedEnvironment.call_binop(self, context,90 operator, left, right)91 92 Make sure to always call into the super method, even if you are not93-intercepting the call. Jinja2 might internally call the method to93+intercepting the call. Jinja might internally call the method to94 evaluate expressions.modified:docs/switching.rst+31 added-31 removed
2 unmodified lines3 4 .. highlight:: html+jinja5 6 If you have used a different template engine in the past and want to switch7-to Jinja2 here is a small guide that shows the basic syntactic and semantic7+to Jinja here is a small guide that shows the basic syntactic and semantic8 changes between some common, similar text template engines for Python.9 10-Jinja111-------10+Jinja 111+-------12 13-Jinja2 is mostly compatible with Jinja1 in terms of API usage and template14-syntax. The differences between Jinja1 and 2 are explained in the following13+Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template14+syntax. The differences between Jinja 1 and 2 are explained in the following15 list.16 17 API18 ~~~19 20 Loaders21- 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>`.27 28 Loading 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.33 34 Automatic 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.41 42 i18n43- 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`.47 48 Internal 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.53 54 Sandbox55- 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`.58 59 Context60- 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.64 65 Filters and Tests3 unmodified lines69 70 Templates71 ~~~~~~~~~72 73-Jinja2 has mostly the same syntax as Jinja1. What's different is that73+Jinja 2 has mostly the same syntax as Jinja 1. What's different is that74 macros require parentheses around the argument list now.75 76-Additionally Jinja2 allows dynamic inheritance now and dynamic includes.76+Additionally Jinja 2 allows dynamic inheritance now and dynamic includes.77 The old helper function `rendertemplate` is gone now, `include` can be used78 instead. Includes no longer import macros and variable assignments, for79 that the new `import` tag is used. This concept is explained in the80 :ref:`import` documentation.6 unmodified lines87 Django88 ------89 90 If you have previously worked with Django templates, you should find91-Jinja2 very familiar. In fact, most of the syntax elements look and91+Jinja very familiar. In fact, most of the syntax elements look and92 work the same.93 94-However, Jinja2 provides some more syntax elements covered in the94+However, Jinja provides some more syntax elements covered in the95 documentation and some work a bit different.96 97 This section covers the template changes. As the API is fundamentally98 different we won't cover it here.19 unmodified lines118 119 Filter Arguments120 ~~~~~~~~~~~~~~~~121 122-Jinja2 provides more than one argument for filters. Also the syntax for122+Jinja provides more than one argument for filters. Also the syntax for123 argument passing is different. A template that looks like this in Django::124 125 {{ items|join:", " }}126 18 unmodified lines145 146 Loops147 ~~~~~148 149-For loops work very similarly to Django, but notably the Jinja2 special149+For loops work very similarly to Django, but notably the Jinja special150 variable for the loop context is called `loop`, not `forloop` as in Django.151 152-In addition, the Django `empty` argument is called `else` in Jinja2. For152+In addition, the Django `empty` argument is called `else` in Jinja. For153 example, the Django template::154 155 {% for item in items %}156 {{ item }}34 unmodified lines191 ----192 193 .. highlight:: html+mako194 195-If you have used Mako so far and want to switch to Jinja2 you can configure196-Jinja2 to look more like Mako:195+If you have used Mako so far and want to switch to Jinja you can configure196+Jinja to look more like Mako:197 198 .. sourcecode:: python199 200 env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')201 202-With an environment configured like that, Jinja2 should be able to interpret203-a small subset of Mako templates. Jinja2 does not support embedded Python202+With an environment configured like that, Jinja should be able to interpret203+a small subset of Mako templates. Jinja does not support embedded Python204 code, 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.206 The following Mako template::207 208 <%inherit file="layout.html" />209 <%def name="title()">Page Title</%def>2 unmodified lines212 <li>${item}</li>213 % endfor214 </ul>215 216-Looks like this in Jinja2 with the above configuration::216+Looks like this in Jinja with the above configuration::217 218 <% extends "layout.html" %>219 <% block title %>Page Title<% endblock %>220 <% block body %>6 unmodified linesmodified:docs/templates.rst+9 added-9 removed
103 unmodified lines104 .. _notes-on-subscriptions:105 106 .. admonition:: Implementation107 108- 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:110 111 - check for an attribute called `bar` on `foo`112 (``getattr(foo, 'bar')``)131 unmodified lines244 245 If :ref:`line-statements` are enabled, they strip leading whitespace246 automatically up to the beginning of the line.247 248-By default, Jinja2 also removes trailing newlines. To keep single248+By default, Jinja also removes trailing newlines. To keep single249 trailing newlines, configure Jinja to `keep_trailing_newline`.250 251 .. admonition:: Note252 239 unmodified lines492 493 Named Block End-Tags494 ~~~~~~~~~~~~~~~~~~~~495 496-Jinja2 allows you to put the name of the block after the end tag for better496+Jinja allows you to put the name of the block after the end tag for better497 readability::498 499 {% block sidebar %}500 {% block inner_sidebar %}97 unmodified lines598 still take place and result in double-escaped characters. If you know599 you have data that is already safe but not marked, be sure to wrap it in600 ``Markup`` or use the ``|safe`` filter.601 602-Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template602+Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template603 data that is marked as safe.604 605 String literals in templates with automatic escaping are considered unsafe606 because native Python strings (``str``, ``unicode``, ``basestring``) are not139 unmodified lines746 writing `{% set outer_loop = loop %}` after the loop that we want to747 use recursively. Then, we can call it using `{{ outer_loop(...) }}`748 749 Please note that assignments in loops will be cleared at the end of the750-iteration and cannot outlive the loop scope. Older versions of Jinja2 had750+iteration and cannot outlive the loop scope. Older versions of Jinja had751 a bug where in some circumstances it appeared that assignments would work.752 This is not supported. See :ref:`assignments` for more information about753 how to deal with this.754 168 unmodified lines923 924 Filters925 ~~~~~~~926 927-Filter sections allow you to apply regular Jinja2 filters on a block of927+Filter sections allow you to apply regular Jinja filters on a block of928 template data. Just wrap the code in the special `filter` section::929 930 {% filter upper %}931 This text becomes uppercase156 unmodified lines1088 1089 Import1090 ~~~~~~1091 1092-Jinja2 supports putting often used code into macros. These macros can go into1092+Jinja supports putting often used code into macros. These macros can go into1093 different templates and get imported from there. This works similarly to the1094 import statements in Python. It's important to know that imports are cached1095 and imported templates don't have access to the current template variables,1096 just the globals by default. For more details about context behavior of468 unmodified lines1565 1566 Extensions1567 ----------1568 1569-The following sections cover the built-in Jinja2 extensions that may be1569+The following sections cover the built-in Jinja extensions that may be1570 enabled by an application. An application could also provide further1571 extensions not covered by this documentation; in which case there should1572 be a separate document explaining said :ref:`extensions1573 <jinja-extensions>`.199 unmodified lines1773 behavior of referencing one variable to another had some unintended1774 consequences. In particular one variable could refer to another defined1775 in the same with block's opening statement. This caused issues with the1776 cleaned up scoping behavior and has since been improved. In particular1777-in newer Jinja2 versions the following code always refers to the variable1777+in newer Jinja versions the following code always refers to the variable1778 `a` from outside the `with` block::1779 1780 {% with a={}, b=a.attribute %}...{% endwith %}1781 39 unmodified linesmodified:docs/tricks.rst+2 added-2 removed
1 unmodified line2 ===============3 4 .. highlight:: html+jinja5 6-This part of the documentation shows some tips and tricks for Jinja26+This part of the documentation shows some tips and tricks for Jinja7 templates.8 9 10 .. _null-master-fallback:11 12 Null-Master Fallback13 --------------------14 15-Jinja2 supports dynamic inheritance and does not distinguish between parent15+Jinja supports dynamic inheritance and does not distinguish between parent16 and child template as long as no `extends` tag is visited. While this leads17 to the surprising behavior that everything before the first `extends` tag18 including whitespace is printed out instead of being ignored, it can be used19 for a neat trick.81 unmodified linesmodified:examples/rwbench/django/layout.html+1 added-1 removed
7 unmodified lines8 <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 linesmodified:examples/rwbench/genshi/layout.html+1 added-1 removed
9 unmodified lines10 <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 linesmodified:examples/rwbench/jinja/layout.html+1 added-1 removed
7 unmodified lines8 <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 linesmodified:examples/rwbench/mako/layout.html+1 added-1 removed
7 unmodified lines8 <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 linesmodified:examples/rwbench/rwbench.py+2 added-2 removed
1 unmodified line2 """3 RealWorldish Benchmark4 ~~~~~~~~~~~~~~~~~~~~~~5 6- 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!9 10 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.101 unmodified linesmodified: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 """6 import sys7 import cgi426 unmodified linesmodified:ext/django2jinja/django2jinja.py+1 added-1 removed
1 unmodified line2 """3 Django to Jinja4 ~~~~~~~~~~~~~~~5 6- Helper module that can convert django templates into Jinja2 templates.6+ Helper module that can convert django templates into Jinja templates.7 8 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 linesmodified:ext/Vim/jinja.vim+1 added-1 removed
8 unmodified lines9 " 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)14 15 " .vimrc variable to disable html highlighting16 if !exists('g:jinja_syntax_html')17 let g:jinja_syntax_html=1121 unmodified linesmodified:ext/djangojinja2.py+5 added-5 removed
1 unmodified line2 """3 djangojinja24 ~~~~~~~~~~~~5 6- Adds support for Jinja2 to Django.6+ Adds support for Jinja to Django.7 8 Configuration variables:9 10 ======================= =============================================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 ======================= =============================================17 18 :copyright: (c) 2009 by the Jinja Team.19 :license: BSD.12 unmodified lines32 _jinja_env = None33 34 35 def 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_env41 42 43 def 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 linesmodified:ext/inlinegettext.py+1 added-1 removed
1 unmodified line2 """3 Inline Gettext4 ~~~~~~~~~~~~~~5 6- 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.8 9 :copyright: (c) 2009 by the Jinja Team.10 :license: BSD.68 unmodified linesmodified:jinja2/__init__.py+2 added-2 removed
1 unmodified line2 """3 jinja24 ~~~~~~5 6- 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.9 10 Nutshell11 --------12 13- Here a small example of a Jinja2 template::13+ Here a small example of a Jinja template::14 15 {% extends 'base.html' %}16 {% block title %}Memberlist{% endblock %}17 {% block content %}55 unmodified linesmodified:jinja2/bccache.py+2 added-2 removed
138 unmodified lines139 with open(filename, 'wb') as f:140 bucket.write_bytecode(f)141 142 A more advanced version of a filesystem based bytecode cache is part of143- Jinja2.143+ Jinja.144 """145 146 def load_bytecode(self, bucket):147 """Subclasses have to override this method to load bytecode into a9 unmodified lines157 """158 raise NotImplementedError()159 160 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 linesmodified:jinja2/environment.py+1 added-1 removed
483 unmodified lines484 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.487 488- 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 linesmodified:jinja2/ext.py+3 added-3 removed
98 unmodified lines99 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`.102 103- 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 stream59 unmodified lines167 return ngettext168 169 170 class InternationalizationExtension(Extension):171- """This extension adds gettext support to Jinja2."""171+ """This extension adds gettext support to Jinja."""172 tags = {'trans'}173 174 # TODO: the i18n extension is currently reevaluating values in a few175 # situations. Take this example:239 unmodified lines415 return nodes.Output([node])416 417 418 class 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 linesmodified:jinja2/filters.py+1 added-1 removed
666 unmodified lines667 -> "foo bar baz qux"668 {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}669 -> "foo bar..."670 671- 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 linesmodified:jinja2/nodes.py+1 added-1 removed
103 unmodified lines104 return ctx105 106 107 class 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:110 111 - :class:`Stmt`: statements112 - :class:`Expr`: expressions892 unmodified linesmodified:jinja2/parser.py+2 added-2 removed
28 unmodified lines29 }30 31 32 class 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 """36 37 def __init__(self, environment, source, name=None, filename=None,356 unmodified lines394 return node395 396 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 linesmodified:jinja2/tests.py+2 added-2 removed
85 unmodified lines86 """87 return value is True88 89 90-# NOTE: The existing Jinja2 'number' test matches booleans and floats90+# NOTE: The existing 'number' test matches booleans and floats91 def test_integer(value):92 """Return true if the object is an integer.93 94 .. versionadded:: 2.1195 """96 return isinstance(value, integer_types) and value is not True and value is not False97 98 99-# NOTE: The existing Jinja2 'number' test matches booleans and integers99+# NOTE: The existing 'number' test matches booleans and integers100 def test_float(value):101 """Return true if the object is a float.102 103 .. versionadded:: 2.11118 unmodified linesmodified:jinja2/utils.py+2 added-2 removed
108 unmodified lines109 pass110 111 112 def 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_environments551 unmodified linesmodified: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+ ~~~~~~~~~~~~~~~~~~~~~6 7- Helper script for internal Jinja2 debugging. Requires Werkzeug.7+ Helper script for internal Jinja debugging. Requires Werkzeug.8 9 :copyright: Copyright 2010 by Armin Ronacher.10 :license: BSD.11 """32 unmodified linesmodified:CHANGES.rst+9 added-9 removed
256 unmodified lines257 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 argument37 unmodified lines303 - 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 reloaded112 unmodified lines424 - 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 lines497 - 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 lines580 -------------581 582 Released 2009-09-14583 584-- Fixes some smaller problems for Jinja2 on Jython.584+- Fixes some smaller problems for Jinja on Jython.585 586 587 Version 2.2588 -----------97 unmodified lines686 --------------687 688 Released 2008-06-09689 690-- First release of Jinja2690+- First release of Jinja 2.