Skip to content
Myr

rename imports to jinja

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 eac9acb · Browse files · 57 files+367 added−393 removed
This commit

State

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

Diff stats

57 files+367 added−393 removed

  • tests:+166 added−168 removed
  • other:+201 added−225 removed

57 files+367 added−393 removed

modified:docs/examples/cache_extension.py+2 added-2 removed
1from jinja2 import nodes2from jinja2.ext import Extension1from jinja import nodes2from jinja.ext import Extension345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.
48 unmodified lines
modified:docs/examples/inline_gettext_extension.py+4 added-4 removed
1# -*- coding: utf-8 -*-2import re34from jinja2.exceptions import TemplateSyntaxError5from jinja2.ext import Extension6from jinja2.lexer import count_newlines7from jinja2.lexer import Token4from jinja.exceptions import TemplateSyntaxError5from jinja.ext import Extension6from jinja.lexer import count_newlines7from jinja.lexer import Token8910_outside_re = re.compile(r"\\?(gettext|_)\(")11_inside_re = re.compile(r"\\?[()]")
62 unmodified lines
modified:docs/api.rst+48 added-48 removed
1API2===34.. module:: jinja24.. module:: jinja5 :noindex:6 :synopsis: public Jinja API78This document describes the API to Jinja and not the template language. It
17 unmodified lines
2627The simplest way to configure Jinja to load templates for your application28looks roughly like this::2930 from jinja2 import Environment, PackageLoader, select_autoescape30 from jinja import Environment, PackageLoader, select_autoescape31 env = Environment(32 loader=PackageLoader('yourapplication', 'templates'),33 autoescape=select_autoescape(['html', 'xml'])34 )
106 unmodified lines
141 .. attribute:: sandboxed142143 If the environment is sandboxed this attribute is `True`. For the144 sandbox mode have a look at the documentation for the145 :class:`~jinja2.sandbox.SandboxedEnvironment`.145 :class:`~jinja.sandbox.SandboxedEnvironment`.146147 .. attribute:: filters148149 A dict of filters for this environment. As long as no template was
31 unmodified lines
181182 The context used for templates. This should not be changed183 in most cases, unless you need to modify internals of how184 template variables are handled. For details, see185 :class:`~jinja2.runtime.Context`.185 :class:`~jinja.runtime.Context`.186187 .. automethod:: overlay([options])188189 .. method:: undefined([hint, obj, name, exc])
60 unmodified lines
250251 .. automethod:: generate_async([context])252253254.. autoclass:: jinja2.environment.TemplateStream()254.. autoclass:: jinja.environment.TemplateStream()255 :members: disable_buffering, enable_buffering, dump256257258Autoescaping
7 unmodified lines
266future. It's recommended to configure a sensible default for267autoescaping. This makes it possible to enable and disable autoescaping268on a per-template basis (HTML versus text for instance).269270.. autofunction:: jinja2.select_autoescape270.. autofunction:: jinja.select_autoescape271272Here a recommended setup that enables autoescaping for templates ending273in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default274for all other extensions. You can use the :func:`~jinja2.select_autoescape`274for all other extensions. You can use the :func:`~jinja.select_autoescape`275function for this::276277 from jinja2 import Environment, select_autoescape277 from jinja import Environment, select_autoescape278 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),279 loader=PackageLoader('mypackage'))280281The :func:`~jinja.select_autoescape` function returns a function that
41 unmodified lines
323324The closest to regular Python behavior is the :class:`StrictUndefined` which325disallows all operations beside testing if it's an undefined object.326327.. autoclass:: jinja2.Undefined()327.. autoclass:: jinja.Undefined()328329 .. attribute:: _undefined_hint330331 Either `None` or an unicode string with the error message for
19 unmodified lines
351 When called with any arguments this method raises352 :attr:`_undefined_exception` with an error message generated353 from the undefined hints stored on the undefined object.354355.. autoclass:: jinja2.ChainableUndefined()355.. autoclass:: jinja.ChainableUndefined()356357.. autoclass:: jinja2.DebugUndefined()357.. autoclass:: jinja.DebugUndefined()358359.. autoclass:: jinja2.StrictUndefined()359.. autoclass:: jinja.StrictUndefined()360361There is also a factory function that can decorate undefined objects to362implement logging on failures:363364.. autofunction:: jinja2.make_logging_undefined364.. autofunction:: jinja.make_logging_undefined365366Undefined objects are created by calling :attr:`undefined`.367368.. admonition:: Implementation
23 unmodified lines
392393The Context394-----------395396.. autoclass:: jinja2.runtime.Context()396.. autoclass:: jinja.runtime.Context()397 :members: resolve, get_exported, get_all398399 .. attribute:: parent400
35 unmodified lines
436 .. attribute:: eval_ctx437438 The current :ref:`eval-context`.439440 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)440 .. automethod:: jinja.runtime.Context.call(callable, \*args, \**kwargs)441442443.. admonition:: Implementation444
18 unmodified lines
463size by default and templates are automatically reloaded.464All loaders are subclasses of :class:`BaseLoader`. If you want to create your465own loader, subclass :class:`BaseLoader` and override `get_source`.466467.. autoclass:: jinja2.BaseLoader467.. autoclass:: jinja.BaseLoader468 :members: get_source, load469470Here a list of the builtin loaders Jinja provides:471472.. autoclass:: jinja2.FileSystemLoader472.. autoclass:: jinja.FileSystemLoader473474.. autoclass:: jinja2.PackageLoader474.. autoclass:: jinja.PackageLoader475476.. autoclass:: jinja2.DictLoader476.. autoclass:: jinja.DictLoader477478.. autoclass:: jinja2.FunctionLoader478.. autoclass:: jinja.FunctionLoader479480.. autoclass:: jinja2.PrefixLoader480.. autoclass:: jinja.PrefixLoader481482.. autoclass:: jinja2.ChoiceLoader482.. autoclass:: jinja.ChoiceLoader483484.. autoclass:: jinja2.ModuleLoader484.. autoclass:: jinja.ModuleLoader485486487.. _bytecode-cache:488
9 unmodified lines
498the application.499500To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.501502.. autoclass:: jinja2.BytecodeCache502.. autoclass:: jinja.BytecodeCache503 :members: load_bytecode, dump_bytecode, clear504505.. autoclass:: jinja2.bccache.Bucket505.. autoclass:: jinja.bccache.Bucket506 :members: write_bytecode, load_bytecode, bytecode_from_string,507 bytecode_to_string, reset508509 .. attribute:: environment
10 unmodified lines
520521522Builtin bytecode caches:523524.. autoclass:: jinja2.FileSystemBytecodeCache524.. autoclass:: jinja.FileSystemBytecodeCache525526.. autoclass:: jinja2.MemcachedBytecodeCache526.. autoclass:: jinja.MemcachedBytecodeCache527528529Async Support530-------------
37 unmodified lines
568569Starting with Jinja 2.9 policies can be configured on the environment570which can slightly influence how filters and other template constructs571behave. They can be configured with the572:attr:`~jinja2.Environment.policies` attribute.572:attr:`~jinja.Environment.policies` attribute.573574Example::575576 env.policies['urlize.rel'] = 'nofollow noopener'
48 unmodified lines
625626These helper functions and classes are useful if you add custom filters or627functions to a Jinja environment.628629.. autofunction:: jinja2.environmentfilter629.. autofunction:: jinja.environmentfilter630631.. autofunction:: jinja2.contextfilter631.. autofunction:: jinja.contextfilter632633.. autofunction:: jinja2.evalcontextfilter633.. autofunction:: jinja.evalcontextfilter634635.. autofunction:: jinja2.environmentfunction635.. autofunction:: jinja.environmentfunction636637.. autofunction:: jinja2.contextfunction637.. autofunction:: jinja.contextfunction638639.. autofunction:: jinja2.evalcontextfunction639.. autofunction:: jinja.evalcontextfunction640641.. function:: escape(s)642643 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
2 unmodified lines
646 that do have an HTML representation such as already escaped data.647648 The return value is a :class:`Markup` string.649650.. autofunction:: jinja2.clear_caches650.. autofunction:: jinja.clear_caches651652.. autofunction:: jinja2.is_undefined652.. autofunction:: jinja.is_undefined653654.. autoclass:: jinja2.Markup([string])654.. autoclass:: jinja.Markup([string])655 :members: escape, unescape, striptags656657.. admonition:: Note658
4 unmodified lines
663664Exceptions665----------666667.. autoexception:: jinja2.TemplateError667.. autoexception:: jinja.TemplateError668669.. autoexception:: jinja2.UndefinedError669.. autoexception:: jinja.UndefinedError670671.. autoexception:: jinja2.TemplateNotFound671.. autoexception:: jinja.TemplateNotFound672673.. autoexception:: jinja2.TemplatesNotFound673.. autoexception:: jinja.TemplatesNotFound674675.. autoexception:: jinja2.TemplateSyntaxError675.. autoexception:: jinja.TemplateSyntaxError676677 .. attribute:: message678679 The error message as utf-8 bytestring.
14 unmodified lines
694 The reason why the filename and error message are bytestrings and not695 unicode strings is that Python 2.x is not using unicode for exceptions696 and tracebacks as well as the compiler. This will change with Python 3.697698.. autoexception:: jinja2.TemplateRuntimeError698.. autoexception:: jinja.TemplateRuntimeError699700.. autoexception:: jinja2.TemplateAssertionError700.. autoexception:: jinja.TemplateAssertionError701702703.. _writing-filters:704
33 unmodified lines
738paragraphs and marks the return value as safe HTML string if autoescaping is739enabled::740741 import re742 from jinja2 import evalcontextfilter, Markup, escape742 from jinja import evalcontextfilter, Markup, escape743744 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')745746 @evalcontextfilter
57 unmodified lines
804must only happen with a :class:`nodes.EvalContextModifier` and805:class:`nodes.ScopedEvalContextModifier` from an extension, not on the806eval context object itself.807808.. autoclass:: jinja2.nodes.EvalContext808.. autoclass:: jinja.nodes.EvalContext809810 .. attribute:: autoescape811812 `True` or `False` depending on if autoescaping is active or not.
114 unmodified lines
927could help applications to implement more advanced template concepts. All928the functions of the meta API operate on an abstract syntax tree as929returned by the :meth:`Environment.parse` method.930931.. autofunction:: jinja2.meta.find_undeclared_variables931.. autofunction:: jinja.meta.find_undeclared_variables932933.. autofunction:: jinja2.meta.find_referenced_templates933.. autofunction:: jinja.meta.find_referenced_templates
modified:docs/conf.py+2 added-2 removed
4 unmodified lines
56project = "Jinja"7copyright = "2007 Pallets"8author = "Pallets"9release, version = get_version("Jinja2")9release, version = get_version("Jinja")1011# General --------------------------------------------------------------1213master_doc = "index"
14 unmodified lines
28html_context = {29 "project_links": [30 ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"),31 ProjectLink("Jinja Website", "https://palletsprojects.com/p/jinja/"),32 ProjectLink("PyPI releases", "https://pypi.org/project/Jinja2/"),32 ProjectLink("PyPI releases", "https://pypi.org/project/Jinja/"),33 ProjectLink("Source Code", "https://github.com/pallets/jinja/"),34 ProjectLink("Issue Tracker", "https://github.com/pallets/jinja/issues/"),35 ]36}
16 unmodified lines
modified:docs/extensions.rst+26 added-26 removed
12 unmodified lines
1314Extensions 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 following17``extensions`` parameter of the :class:`~jinja.Environment` constructor. The following18example creates a Jinja environment with the i18n extension loaded::1920 jinja_env = Environment(extensions=['jinja2.ext.i18n'])20 jinja_env = Environment(extensions=['jinja.ext.i18n'])212223.. _i18n-extension:2425i18n Extension26--------------2728**Import name:** ``jinja2.ext.i18n``28**Import name:** ``jinja.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or31`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that32marks a block as translatable and calls ``gettext``.
7 unmodified lines
4041After enabling the extension, the environment provides the following42additional methods:4344.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)44.. method:: jinja.Environment.install_gettext_translations(translations, newstyle=False)4546 Installs a translation globally for the environment. The47 ``translations`` object must implement ``gettext`` and ``ngettext``48 (or ``ugettext`` and ``ungettext`` for Python 2).
1 unmodified line
50 and `Babel`_\s ``Translations`` are supported.5152 .. versionchanged:: 2.5 Added new-style gettext support.5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)54.. method:: jinja.Environment.install_null_translations(newstyle=False)5556 Install no-op gettext functions. This is useful if you want to57 prepare the application for internationalization but don't want to58 implement the full system yet.5960 .. versionchanged:: 2.5 Added new-style gettext support.6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)62.. method:: jinja.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 Install the given ``gettext`` and ``ngettext`` callables into the65 environment. They should behave exactly like66 :func:`gettext.gettext` and :func:`gettext.ngettext` (or
3 unmodified lines
70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.5 Added new-style gettext support.7374.. method:: jinja2.Environment.uninstall_gettext_translations()74.. method:: jinja.Environment.uninstall_gettext_translations()7576 Uninstall the environment's globally installed translation.7778.. method:: jinja2.Environment.extract_translations(source)78.. method:: jinja.Environment.extract_translations(source)7980 Extract localizable strings from the given template node or source.8182 For every string found this function yields a ``(lineno, function,
16 unmodified lines
99100.. code-block:: python101102 translations = get_gettext_translations()103 env = Environment(extensions=["jinja2.ext.i18n"])103 env = Environment(extensions=["jinja.ext.i18n"])104 env.install_gettext_translations(translations)105106The ``get_gettext_translations`` function would return the translator107for the current configuration, for example by using ``gettext.find``.
73 unmodified lines
181182Expression Statement183--------------------184185**Import name:** ``jinja2.ext.do``185**Import name:** ``jinja.ext.do``186187The "do" aka expression-statement extension adds a simple ``do`` tag to the188template engine that works like a variable expression but ignores the189return value.
2 unmodified lines
192193Loop Controls194-------------195196**Import name:** ``jinja2.ext.loopcontrols``196**Import name:** ``jinja.ext.loopcontrols``197198This extension adds support for ``break`` and ``continue`` in loops. After199enabling, Jinja provides those two keywords which work exactly like in200Python.
2 unmodified lines
203204With Statement205--------------206207**Import name:** ``jinja2.ext.with_``207**Import name:** ``jinja.ext.with_``208209.. versionchanged:: 2.9210211 This extension is now built-in and no longer does anything.
2 unmodified lines
214215Autoescape Extension216--------------------217218**Import name:** ``jinja2.ext.autoescape``218**Import name:** ``jinja.ext.autoescape``219220.. versionchanged:: 2.9221222 This extension was removed and is now built-in. Enabling the
4 unmodified lines
227228Debug Extension229---------------230231**Import name:** ``jinja2.ext.debug``231**Import name:** ``jinja.ext.debug``232233Adds a ``{% debug %}`` tag to dump the current context as well as the234available filters and tests. This is useful to see what's available to235use in the template without setting up a debugger.
3 unmodified lines
239240Writing Extensions241------------------242243.. module:: jinja2.ext243.. module:: jinja.ext244245By 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 are
20 unmodified lines
268 :language: python269270And here is how you use it in an environment::271272 from jinja2 import Environment272 from jinja import Environment273 from cachelib import SimpleCache274275 env = Environment(extensions=[FragmentCacheExtension])276 env.fragment_cache = SimpleCache()
35 unmodified lines
312313Extension314~~~~~~~~~315316Extensions always have to extend the :class:`jinja2.ext.Extension` class:316Extensions always have to extend the :class:`jinja.ext.Extension` class:317318.. autoclass:: Extension319 :members: preprocess, filter_stream, parse, attr, call_method320
14 unmodified lines
335The parser passed to :meth:`Extension.parse` provides ways to parse336expressions of different types. The following methods may be used by337extensions:338339.. autoclass:: jinja2.parser.Parser339.. autoclass:: jinja.parser.Parser340 :members: parse_expression, parse_tuple, parse_assign_target,341 parse_statements, free_identifier, fail342343 .. attribute:: filename
8 unmodified lines
352 The load name of the template.353354 .. attribute:: stream355356 The current :class:`~jinja2.lexer.TokenStream`356 The current :class:`~jinja.lexer.TokenStream`357358.. autoclass:: jinja2.lexer.TokenStream358.. autoclass:: jinja.lexer.TokenStream359 :members: push, look, eos, skip, __next__, next_if, skip_if, expect360361 .. attribute:: current362363 The current :class:`~jinja2.lexer.Token`.363 The current :class:`~jinja.lexer.Token`.364365.. autoclass:: jinja2.lexer.Token365.. autoclass:: jinja.lexer.Token366 :members: test, test_any367368 .. attribute:: lineno369
10 unmodified lines
380381There is also a utility function in the lexer module that can count newline382characters in strings:383384.. autofunction:: jinja2.lexer.count_newlines384.. autofunction:: jinja.lexer.count_newlines385386387AST388~~~
5 unmodified lines
394395The list below describes all nodes that are currently available. The AST may396change between Jinja versions but will stay backwards compatible.397398For more information have a look at the repr of :meth:`jinja2.Environment.parse`.398For more information have a look at the repr of :meth:`jinja.Environment.parse`.399400.. module:: jinja2.nodes400.. module:: jinja.nodes401402.. jinja:nodes:: jinja2.nodes.Node402.. jinja:nodes:: jinja.nodes.Node403404.. autoexception:: Impossible
modified:docs/faq.rst+1 added-1 removed
143 unmodified lines
144 from google.appengine.tools.devappserver2.python import sandbox145 sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']146147Credit for this snippet goes to `Thomas Johansson148<https://stackoverflow.com/questions/3086091/debug-jinja2-in-google-app-engine/3694434#3694434>`_148<https://stackoverflow.com/a/3694434>`_149150Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151-----------------------------------------------------------152
43 unmodified lines
modified:docs/integration.rst+4 added-4 removed
12 unmodified lines
13Babel Integration14-----------------1516Jinja provides support for extracting gettext messages from templates via a17`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel17`Babel`_ extractor entry point called `jinja.ext.babel_extract`. The Babel18support is implemented as part of the :ref:`i18n-extension` extension.1920Gettext messages extracted from both `trans` tags and code expressions.21
1 unmodified line
23in its Babel extraction method `mapping file`_:2425.. sourcecode:: ini2627 [jinja2: **/templates/**.html]27 [jinja: **/templates/**.html]28 encoding = utf-82930The syntax related options of the :class:`Environment` are also available as31configuration values in the mapping file. For example to tell the extraction32that templates use ``%`` as `line_statement_prefix` you can use this code:3334.. sourcecode:: ini3536 [jinja2: **/templates/**.html]36 [jinja: **/templates/**.html]37 encoding = utf-838 line_statement_prefix = %3940:ref:`jinja-extensions` may also be defined by passing a comma separated list
19 unmodified lines
6061The template engine is configured in `config/environment.py`. The configuration62for Jinja looks something like that::6364 from jinja2 import Environment, PackageLoader64 from jinja import Environment, PackageLoader65 config['pylons.app_globals'].jinja_env = Environment(66 loader=PackageLoader('yourapplication', 'templates')67 )68
38 unmodified lines
modified:docs/intro.rst+12 added-34 removed
7 unmodified lines
8Django, 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.111213Prerequisites14-------------1515Jinja 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.16Jinja works with Python >= 3.5 and 2.7.1720If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21need `setuptools`_ or `distribute`_ installed at runtime.18Jinja depends on `MarkupSafe`_. If you install via ``pip`` it will be19installed automatically.2021.. _MarkupSafe: https://markupsafe.palletsprojects.com/222324Installation25------------2627You can install the most recent Jinja version using `pip`_::2828 pip install Jinja229 pip install Jinja3031This will install Jinja in your Python installation's site-packages directory.3232Installing the development version33~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~34351. Install `git`_362. ``git clone git://github.com/pallets/jinja.git``373. ``cd jinja2``384. ``ln -s jinja2 /usr/lib/python2.X/site-packages``3940As an alternative to steps 4 you can also do ``python setup.py develop``41which will install the package via `distribute` in development mode. This also42has the advantage that the C extensions are compiled.4344.. _distribute: https://pypi.org/project/distribute/45.. _setuptools: https://pypi.org/project/setuptools/33.. _pip: https://pypi.org/project/pip/47.. _git: https://git-scm.com/343550MarkupSafe Dependency51~~~~~~~~~~~~~~~~~~~~~5253As 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/5736Basic API Usage37---------------3839This section gives you a brief introduction to the Python API for Jinja40templates.4142The most basic way to create a template and render it is through65:class:`~jinja2.Template`. This however is not the recommended way to43:class:`~jinja.Template`. This however is not the recommended way to44work with it if your templates are not loaded from strings but the file45system or another data source:4669>>> from jinja2 import Template47>>> from jinja import Template48>>> template = Template('Hello {{ name }}!')49>>> template.render(name='John Doe')50u'Hello John Doe!'5174By creating an instance of :class:`~jinja2.Template` you get back a new template75object that provides a method called :meth:`~jinja2.Template.render` which when52By creating an instance of :class:`~jinja.Template` you get back a new template53object that provides a method called :meth:`~jinja.Template.render` which when54called with a dict or keyword arguments expands the template. The dict55or keywords arguments passed to the template are the so-called "context"56of the template.57
3 unmodified lines
modified:docs/nativetypes.rst+2 added-2 removed
1.. module:: jinja2.nativetypes1.. module:: jinja.nativetypes23.. _nativetypes:45Native Python Types6===================78The default :class:`~jinja2.Environment` renders templates to strings. With8The default :class:`~jinja.Environment` renders templates to strings. With9:class:`NativeEnvironment`, rendering a template produces a native Python type.10This is useful if you are using Jinja outside the context of creating text11files. For example, your code may have an intermediate step where users may use12templates to define values that will then be passed to a traditional string
52 unmodified lines
modified:docs/sandbox.rst+2 added-2 removed
15 unmodified lines
1617API18---1920.. module:: jinja2.sandbox20.. module:: jinja.sandbox2122.. autoclass:: SandboxedEnvironment([options])23 :members: is_safe_attribute, is_safe_callable, default_binop_table,24 default_unop_table, intercepted_binops, intercepted_unops,
51 unmodified lines
7677This example shows how the power (``**``) operator can be disabled in78Jinja::7980 from jinja2.sandbox import SandboxedEnvironment80 from jinja.sandbox import SandboxedEnvironment818283 class MyEnvironment(SandboxedEnvironment):84 intercepted_binops = frozenset(['**'])
10 unmodified lines
modified:docs/templates.rst+4 added-4 removed
1423 unmodified lines
14241425List of Builtin Filters1426-----------------------14271428.. jinja:filters:: jinja2.defaults.DEFAULT_FILTERS1428.. jinja:filters:: jinja.defaults.DEFAULT_FILTERS142914301431.. _builtin-tests:14321433List of Builtin Tests1434---------------------14351436.. jinja:tests:: jinja2.defaults.DEFAULT_TESTS1436.. jinja:tests:: jinja.defaults.DEFAULT_TESTS143714381439.. _builtin-globals:1440
289 unmodified lines
1730 <pre>{% debug %}</pre>17311732.. code-block:: text17331734 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,1734 {'context': {'cycler': <class 'jinja.utils.Cycler'>,1735 ...,1736 'namespace': <class 'jinja2.utils.Namespace'>},1736 'namespace': <class 'jinja.utils.Namespace'>},1737 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',1738 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],1739 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',1740 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
80 unmodified lines
modified:examples/basic/cycle.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(6 line_statement_prefix="#", variable_start_string="${", variable_end_string="}"7)
11 unmodified lines
modified:examples/basic/debugger.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import FileSystemLoader3from jinja import Environment4from jinja.loaders import FileSystemLoader56env = Environment(loader=FileSystemLoader("templates"))7tmpl = env.get_template("broken.html")8print(tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]))
modified:examples/basic/inheritance.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import DictLoader3from jinja import Environment4from jinja.loaders import DictLoader56env = Environment(7 loader=DictLoader(8 {
7 unmodified lines
modified:examples/basic/test_filter_and_linestatements.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(6 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"7)
22 unmodified lines
modified:examples/basic/test_loop_filter.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45tmpl = Environment().from_string(6 """\7<ul>
8 unmodified lines
modified:examples/basic/test.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import DictLoader3from jinja import Environment4from jinja.loaders import DictLoader56env = Environment(7 loader=DictLoader(8 {
23 unmodified lines
modified:examples/basic/translate.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(extensions=["jinja2.ext.i18n"])5env = Environment(extensions=["jinja.ext.i18n"])6env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__7env.globals["ngettext"] = lambda s, p, n: {8 "%(count)s user": "%(count)d Benutzer",9 "%(count)s users": "%(count)d Benutzer",
11 unmodified lines
modified:scripts/generate_identifier_pattern.py+2 added-4 removed
56 unmodified lines
57 return "".join(out)585960def main():61 """Build the regex pattern and write it to62 ``jinja2/_identifier.py``.63 """61 """Build the regex pattern and write it to ``_identifier.py``."""62 pattern = build_pattern(collapse_ranges(get_characters()))63 filename = os.path.abspath(66 os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")64 os.path.join(os.path.dirname(__file__), "..", "src", "jinja", "_identifier.py")65 )6667 with open(filename, "w", encoding="utf8") as f:68 f.write("import re\n\n")
8 unmodified lines
modified:src/jinja/bccache.py+22 added-17 removed
21 unmodified lines
22from ._compat import pickle23from ._compat import text_type24from .utils import open_if_exists2526bc_version = 32728# magic version used to only change with new jinja versions. With 2.629# we change this to also take Python version changes into account. The30# reason for this is that Python tends to segfault if fed earlier bytecode31# versions because someone thought it would be a good idea to reuse opcodes32# or make Python incompatible with earlier versions.26bc_version = 427# Magic bytes to identify Jinja bytecode cache files. Contains the28# Python major and minor version to avoid loading incompatible bytecode29# if a project upgrades its Python version.30bc_magic = (34 "j2".encode("ascii")31 b"jinja"32 + pickle.dumps(bc_version, 2)36 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])33 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)34)353637class Bucket(object):
55 unmodified lines
9394class BytecodeCache(object):95 """To implement your own bytecode cache you have to subclass this class96 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of100 these methods are passed a :class:`~jinja2.bccache.Bucket`.97 these methods are passed a :class:`Bucket`.9899 A very basic bytecode cache that saves the bytecode on the file system::100101 from os import path
76 unmodified lines
178 Windows the user's temp directory is used, on UNIX systems a directory179 is created for the user in the system temp directory.180181 The pattern can be used to have multiple separate caches operate on the185 same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``182 same directory. The default pattern is ``'__jinja_%s.cache'``. ``%s``183 is replaced with the cache key.184185 >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')186187 This bytecode cache supports clearing of the cache using the clear method.188189 .. versionchanged:; 2.11190 The default cache directory was renamed to191 ``_jinja-cache-{uid}``. The default filename pattern was renamed192 to ``__jinja_%s.cache``.193 """194193 def __init__(self, directory=None, pattern="__jinja2_%s.cache"):195 def __init__(self, directory=None, pattern="__jinja_%s.cache"):196 if directory is None:197 directory = self._get_default_cache_dir()198 self.directory = directory199 self.pattern = pattern
13 unmodified lines
213 return tmpdir214 if not hasattr(os, "getuid"):215 _unsafe_dir()216215 dirname = "_jinja2-cache-%d" % os.getuid()217 dirname = "_jinja-cache-%d" % os.getuid()218 actual_dir = os.path.join(tmpdir, dirname)219220 try:221 os.mkdir(actual_dir, stat.S_IRWXU)
94 unmodified lines
316317 This bytecode cache does not support clearing of used items in the cache.318 The clear method is a no-operation function.319320 .. versionchanged:: 2.11321 The default prefix was renamed to ``jinja/bytecode/``.322318 .. versionadded:: 2.7319 Added support for ignoring memcache errors through the320 `ignore_memcache_errors` parameter.323 .. versionchanged:: 2.7324 Added support for ignoring memcache errors through the325 ``ignore_memcache_errors`` parameter.326 """327328 def __init__(329 self,330 client,326 prefix="jinja2/bytecode/",331 prefix="jinja/bytecode/",332 timeout=None,333 ignore_memcache_errors=True,334 ):335 self.client = client
23 unmodified lines
modified:src/jinja/compiler.py+2 added-2 removed
713 unmodified lines
714715 from .runtime import __all__ as exported716717 self.writeline("from __future__ import %s" % ", ".join(code_features))718 self.writeline("from jinja2.runtime import " + ", ".join(exported))718 self.writeline("from jinja.runtime import " + ", ".join(exported))719720 if self.environment.is_async:721 self.writeline(722 "from jinja2.asyncsupport import auto_await, "722 "from jinja.asyncsupport import auto_await, "723 "auto_aiter, AsyncLoopContext"724 )725726 # if we want a deferred initialization we cannot move the
1116 unmodified lines
modified:src/jinja/environment.py+6 added-6 removed
216 unmodified lines
217218 `autoescape`219 If set to ``True`` the XML/HTML autoescaping feature is enabled by220 default. For more details about autoescaping see221 :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also221 :class:`~markupsafe.Markup`. This can also222 be a callable that is passed the template name and has to223 return ``True`` or ``False`` depending on autoescape should be224 enabled by default.225
35 unmodified lines
261 """262263 #: if this environment is sandboxed. Modifying this variable won't make264 #: the environment sandboxed though. For a real sandboxed environment265 #: have a look at jinja2.sandbox. This flag alone controls the code265 #: have a look at jinja.sandbox. This flag alone controls the code266 #: generation by the compiler.267 sandboxed = False268269 #: True if the environment is just an overlay
6 unmodified lines
276 #: must not be modified277 shared = False278279 #: the class that is used for code generation. See280 #: :class:`~jinja2.compiler.CodeGenerator` for more information.280 #: :class:`~jinja.compiler.CodeGenerator` for more information.281 code_generator_class = CodeGenerator282283 #: the context class thatis used for templates. See284 #: :class:`~jinja2.runtime.Context` for more information.284 #: :class:`~jinja.runtime.Context` for more information.285 context_class = Context286287 def __init__(288 self,
276 unmodified lines
565 )566567 def _tokenize(self, source, name, filename=None, state=None):568 """Called by the parser to do the preprocessing and filtering569 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.569 for all the extensions. Returns a :class:`~jinja.lexer.TokenStream`.570 """571 source = self.preprocess(source, name, filename)572 stream = self.lexer.tokenize(source, name, filename, state)573 for ext in self.iter_extensions():
679 unmodified lines
1253 return "<%s %s>" % (self.__class__.__name__, name)125412551256class TemplateExpression(object):1257 """The :meth:`jinja2.Environment.compile_expression` method returns an1257 """The :meth:`jinja.Environment.compile_expression` method returns an1258 instance of this object. It encapsulates the expression-like access1259 to the template with an expression it wraps.1260 """1261
100 unmodified lines
modified:src/jinja/ext.py+7 added-7 removed
91 unmodified lines
92 """93 return source9495 def filter_stream(self, stream):96 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used96 """It's passed a :class:`~jinja.lexer.TokenStream` that can be used97 to filter tokens returned. This method has to return an iterable of98 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a99 :class:`~jinja2.lexer.TokenStream`.98 :class:`~jinja.lexer.Token`\\s, but it doesn't have to return a99 :class:`~jinja.lexer.TokenStream`.100 """101 return stream102103 def parse(self, parser):
17 unmodified lines
121 def call_method(122 self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123 ):124 """Call a method of the extension. This is a shortcut for125 :meth:`attr` + :class:`jinja2.nodes.Call`.125 :meth:`attr` + :class:`jinja.nodes.Call`.126 """127 if args is None:128 args = []129 if kwargs is None:
345 unmodified lines
475 <pre>{% debug %}</pre>476477 .. code-block:: text478479 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,479 {'context': {'cycler': <class 'jinja.utils.Cycler'>,480 ...,481 'namespace': <class 'jinja2.utils.Namespace'>},481 'namespace': <class 'jinja.utils.Namespace'>},482 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
36 unmodified lines
522 skipped.523524 This example explains the behavior:525526 >>> from jinja2 import Environment526 >>> from jinja import Environment527 >>> env = Environment()528 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529 >>> list(extract_from_ast(node))530 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
173 unmodified lines
modified:src/jinja/filters.py+3 added-3 removed
436 unmodified lines
437438 {{ ''|default('the string was empty', true) }}439440 .. versionchanged:: 2.11441 It's now possible to configure the :class:`~jinja2.Environment` with442 :class:`~jinja2.ChainableUndefined` to make the `default` filter work441 It's now possible to configure the :class:`~jinja.Environment` with442 :class:`~jinja.ChainableUndefined` to make the `default` filter work443 on nested elements and attributes that may contain undefined values444 in the chain without getting an :exc:`~jinja2.UndefinedError`.444 in the chain without getting an :exc:`~jinja.UndefinedError`.445 """446 if isinstance(value, Undefined) or (boolean and not value):447 return default_value448 return value
934 unmodified lines
modified:src/jinja/lexer.py+1 added-1 removed
395 unmodified lines
396 self.closed = True397398 def expect(self, expr):399 """Expect a given token type and return it. This accepts the same400 argument as :meth:`jinja2.lexer.Token.test`.400 argument as :meth:`jinja.lexer.Token.test`.401 """402 if not self.current.test(expr):403 expr = describe_token_expr(expr)404 if self.current.type is TOKEN_EOF:
437 unmodified lines
modified:src/jinja/loaders.py+2 added-2 removed
44 unmodified lines
4546 A very basic example for a loader that looks up templates on the file47 system could look like this::4849 from jinja2 import BaseLoader, TemplateNotFound49 from jinja import BaseLoader, TemplateNotFound50 from os.path import join, exists, getmtime5152 class MyLoader(BaseLoader):53
468 unmodified lines
522523 has_source_access = False524525 def __init__(self, path):526 package_name = "_jinja2_module_templates_%x" % id(self)526 package_name = "_jinja_module_templates_%x" % id(self)527528 # create a fake module that looks for the templates in the529 # path given.530 mod = _TemplateModule(package_name)
42 unmodified lines
modified:src/jinja/meta.py+2 added-2 removed
30 unmodified lines
31 the context at runtime. Because at compile time it's not known which32 variables will be used depending on the path the execution takes at33 runtime, all variables are returned.3435 >>> from jinja2 import Environment, meta35 >>> from jinja import Environment, meta36 >>> env = Environment()37 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38 >>> meta.find_undeclared_variables(ast) == set(['bar'])39 True
15 unmodified lines
55 iterator over all the hardcoded template extensions, inclusions and56 imports. If dynamic inheritance or inclusion is used, `None` will be57 yielded.5859 >>> from jinja2 import Environment, meta59 >>> from jinja import Environment, meta60 >>> env = Environment()61 >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62 >>> list(meta.find_referenced_templates(ast))63 ['layout.html', None]
38 unmodified lines
modified:src/jinja/nodes.py+5 added-5 removed
935 unmodified lines
936 """Returns the attribute of an extension bound to the environment.937 The identifier is the identifier of the :class:`Extension`.938939 This node is usually constructed by calling the940 :meth:`~jinja2.ext.Extension.attr` method on an extension.940 :meth:`~jinja.ext.Extension.attr` method on an extension.941 """942943 fields = ("identifier", "name")944
10 unmodified lines
955956class InternalName(Expr):957 """An internal name in the compiler. You cannot create these nodes958 yourself but the parser provides a959 :meth:`~jinja2.parser.Parser.free_identifier` method that creates959 :meth:`~jinja.parser.Parser.free_identifier` method that creates960 a new identifier for you. This identifier is not available from the961 template and is not threated specially by the compiler.962 """963
37 unmodified lines
10011002class ContextReference(Expr):1003 """Returns the current template context. It can be used like a1004 :class:`Name` node, with a ``'load'`` ctx and will return the1005 current :class:`~jinja2.runtime.Context` object.1005 current :class:`~jinja.runtime.Context` object.10061007 Here an example that assigns the current template name to a1008 variable named `foo`::10091010 Assign(Name('foo', ctx='store'),1011 Getattr(ContextReference(), 'name'))10121013 This is basically equivalent to using the1014 :func:`~jinja2.contextfunction` decorator when using the1014 :func:`~jinja.contextfunction` decorator when using the1015 high-level API, which causes a reference to the context to be passed1016 as the first argument to a function.1017 """1018
52 unmodified lines
10711072class ScopedEvalContextModifier(EvalContextModifier):1073 """Modifies the eval context and reverts it later. Works exactly like1074 :class:`EvalContextModifier` but will only modify the1075 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1075 :class:`~jinja.nodes.EvalContext` for nodes in the :attr:`body`.1076 """10771078 fields = ("body",)1079
8 unmodified lines
modified:src/jinja/parser.py+2 added-2 removed
121 unmodified lines
122 return self.stream.current.test_any(extra_end_rules)123 return False124125 def free_identifier(self, lineno=None):126 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""126 """Return a new free identifier as :class:`~jinja.nodes.InternalName`."""127 self._last_identifier += 1128 rv = object.__new__(nodes.InternalName)129 nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130 return rv
475 unmodified lines
606 extra_end_rules=None,607 explicit_parentheses=False,608 ):609 """Works like `parse_expression` but if multiple expressions are610 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.610 delimited by a comma a :class:`~jinja.nodes.Tuple` node is created.611 This method could also return a regular expression instead of a tuple612 if no commas where found.613614 The default parsing mode is a full tuple. If `simplified` is `True`
325 unmodified lines
modified:src/jinja/runtime.py+6 added-6 removed
699 unmodified lines
700 True701 >>> foo + 42702 Traceback (most recent call last):703 ...704 jinja2.exceptions.UndefinedError: 'foo' is undefined704 jinja.exceptions.UndefinedError: 'foo' is undefined705 """706707 __slots__ = (708 "_undefined_hint",
216 unmodified lines
925 ''926 >>> foo.bar['baz'] + 42927 Traceback (most recent call last):928 ...929 jinja2.exceptions.UndefinedError: 'foo' is undefined929 jinja.exceptions.UndefinedError: 'foo' is undefined930931 .. versionadded:: 2.11.0932 """933
19 unmodified lines
953 True954 >>> foo + 42955 Traceback (most recent call last):956 ...957 jinja2.exceptions.UndefinedError: 'foo' is undefined957 jinja.exceptions.UndefinedError: 'foo' is undefined958 """959960 __slots__ = ()961
17 unmodified lines
979 >>> foo = StrictUndefined(name='foo')980 >>> str(foo)981 Traceback (most recent call last):982 ...983 jinja2.exceptions.UndefinedError: 'foo' is undefined983 jinja.exceptions.UndefinedError: 'foo' is undefined984 >>> not foo985 Traceback (most recent call last):986 ...987 jinja2.exceptions.UndefinedError: 'foo' is undefined987 jinja.exceptions.UndefinedError: 'foo' is undefined988 >>> foo + 42989 Traceback (most recent call last):990 ...991 jinja2.exceptions.UndefinedError: 'foo' is undefined991 jinja.exceptions.UndefinedError: 'foo' is undefined992 """993994 __slots__ = ()995 __iter__ = (
16 unmodified lines
modified:src/jinja/sandbox.py+1 added-1 removed
195 unmodified lines
196 example this function returns `True` for the `func_code` attribute of197 python objects. This is useful if the environment method198 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199200 >>> from jinja2.sandbox import is_internal_attribute200 >>> from jinja.sandbox import is_internal_attribute201 >>> is_internal_attribute(str, "mro")202 True203 >>> is_internal_attribute(str, "upper")204 False
306 unmodified lines
modified:src/jinja/utils.py+3 added-3 removed
541 unmodified lines
542543 If you want to enable it for all templates created from strings or544 for all templates with `.html` and `.xml` extensions::545546 from jinja2 import Environment, select_autoescape546 from jinja import Environment, select_autoescape547 env = Environment(autoescape=select_autoescape(548 enabled_extensions=('html', 'xml'),549 default_for_string=True,550 ))551552 Example configuration to turn it on at all times except if the template553 ends with `.txt`::554555 from jinja2 import Environment, select_autoescape555 from jinja import Environment, select_autoescape556 env = Environment(autoescape=select_autoescape(557 disabled_extensions=('txt',),558 default_for_string=True,559 default=True,
158 unmodified lines
718def soft_unicode(s):719 from markupsafe import soft_unicode720721 warnings.warn(722 "'jinja2.utils.soft_unicode' will be removed in version 3.0."722 "'jinja.utils.soft_unicode' will be removed in version 3.0."723 " Use 'markupsafe.soft_unicode' instead.",724 DeprecationWarning,725 stacklevel=2,726 )
1 unmodified line
modified:tests/conftest.py+3 added-3 removed
1 unmodified line
2import os34import pytest56from jinja2 import Environment7from jinja2 import loaders8from jinja2.utils import have_async_gen6from jinja import Environment7from jinja import loaders8from jinja.utils import have_async_gen91011def pytest_ignore_collect(path):12 if "async" in path.basename and not have_async_gen:
89 unmodified lines
modified:tests/test_api.py+20 added-20 removed
3 unmodified lines
4import tempfile56import pytest78from jinja2 import ChainableUndefined9from jinja2 import DebugUndefined10from jinja2 import DictLoader11from jinja2 import Environment12from jinja2 import is_undefined13from jinja2 import make_logging_undefined14from jinja2 import meta15from jinja2 import StrictUndefined16from jinja2 import Template17from jinja2 import TemplatesNotFound18from jinja2 import Undefined19from jinja2 import UndefinedError20from jinja2.compiler import CodeGenerator21from jinja2.runtime import Context22from jinja2.utils import contextfunction23from jinja2.utils import Cycler24from jinja2.utils import environmentfunction25from jinja2.utils import evalcontextfunction8from jinja import ChainableUndefined9from jinja import DebugUndefined10from jinja import DictLoader11from jinja import Environment12from jinja import is_undefined13from jinja import make_logging_undefined14from jinja import meta15from jinja import StrictUndefined16from jinja import Template17from jinja import TemplatesNotFound18from jinja import Undefined19from jinja import UndefinedError20from jinja.compiler import CodeGenerator21from jinja.runtime import Context22from jinja.utils import contextfunction23from jinja.utils import Cycler24from jinja.utils import environmentfunction25from jinja.utils import evalcontextfunction262728@pytest.mark.api29@pytest.mark.extended30class TestExtendedAPI(object):31 def test_item_and_attribute(self, env):32 from jinja2.sandbox import SandboxedEnvironment32 from jinja.sandbox import SandboxedEnvironment3334 for env in Environment(), SandboxedEnvironment():35 # the |list is necessary for python336 tmpl = env.from_string("{{ foo.items()|list }}")
116 unmodified lines
153 t = env.from_string("{{ foo }}")154 assert t.render(foo="<foo>") == "<foo>"155156 def test_sandbox_max_range(self, env):157 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE157 from jinja.sandbox import SandboxedEnvironment, MAX_RANGE158159 env = SandboxedEnvironment()160 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")161
271 unmodified lines
modified:tests/test_async.py+7 added-7 removed
1import asyncio23import pytest45from jinja2 import DictLoader6from jinja2 import Environment7from jinja2 import Template8from jinja2.asyncsupport import auto_aiter9from jinja2.exceptions import TemplateNotFound10from jinja2.exceptions import TemplatesNotFound11from jinja2.exceptions import UndefinedError5from jinja import DictLoader6from jinja import Environment7from jinja import Template8from jinja.asyncsupport import auto_aiter9from jinja.exceptions import TemplateNotFound10from jinja.exceptions import TemplatesNotFound11from jinja.exceptions import UndefinedError121314def run(coro):15 loop = asyncio.get_event_loop()
566 unmodified lines
modified:tests/test_asyncfilters.py+2 added-2 removed
1from collections import namedtuple23import pytest45from jinja2 import Environment6from jinja2.utils import Markup5from jinja import Environment6from jinja.utils import Markup789async def make_aiter(iter):10 for item in iter:
214 unmodified lines
modified:tests/test_bytecode_cache.py+6 added-6 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2.bccache import Bucket6from jinja2.bccache import FileSystemBytecodeCache7from jinja2.bccache import MemcachedBytecodeCache8from jinja2.exceptions import TemplateNotFound4from jinja import Environment5from jinja.bccache import Bucket6from jinja.bccache import FileSystemBytecodeCache7from jinja.bccache import MemcachedBytecodeCache8from jinja.exceptions import TemplateNotFound91011@pytest.fixture12def env(package_loader):
39 unmodified lines
5253 b = Bucket(None, "key", "")54 b.code = "code"55 m.dump_bytecode(b)56 assert memcached.key == "jinja2/bytecode/key"56 assert memcached.key == "jinja/bytecode/key"5758 b = Bucket(None, "key", "")59 m.load_bytecode(b)60 assert b.code == "code"
19 unmodified lines
modified:tests/test_core_tags.py+5 added-5 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2 import TemplateRuntimeError7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError4from jinja import DictLoader5from jinja import Environment6from jinja import TemplateRuntimeError7from jinja import TemplateSyntaxError8from jinja import UndefinedError91011@pytest.fixture12def env_trim():
600 unmodified lines
modified:tests/test_debug.py+8 added-8 removed
3 unmodified lines
4from traceback import format_exception56import pytest78from jinja2 import ChoiceLoader9from jinja2 import DictLoader10from jinja2 import Environment11from jinja2 import TemplateSyntaxError8from jinja import ChoiceLoader9from jinja import DictLoader10from jinja import Environment11from jinja import TemplateSyntaxError121314@pytest.fixture15def fs_env(filesystem_loader):
38 unmodified lines
54 lambda: fs_env.get_template("syntaxerror.html"),55 """(?sm)56 File ".*?syntaxerror.html", line 4, in (template|<module>)57 \\{% endif %\\}.*?58(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \58(jinja\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \59was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \60to be closed is 'for'.61 """,62 )
6 unmodified lines
69 test,70 r"""71 File ".*debug.pyc?", line \d+, in test72 raise TemplateSyntaxError\("wtf", 42\)73(jinja2\.exceptions\.)?TemplateSyntaxError: wtf73(jinja\.exceptions\.)?TemplateSyntaxError: wtf74 line 42""",75 )7677 def test_pickleable_syntax_error(self, fs_env):
18 unmodified lines
9697 assert exc_info.value.source is not None9899 def test_local_extraction(self):100 from jinja2.debug import get_template_locals101 from jinja2.runtime import missing100 from jinja.debug import get_template_locals101 from jinja.runtime import missing102103 locals = get_template_locals(104 {105 "l_0_foo": 42,
12 unmodified lines
modified:tests/test_ext.py+32 added-34 removed
1 unmodified line
2import re34import pytest56from jinja2 import contextfunction7from jinja2 import DictLoader8from jinja2 import Environment9from jinja2 import nodes10from jinja2._compat import BytesIO11from jinja2._compat import itervalues12from jinja2._compat import text_type13from jinja2.exceptions import TemplateAssertionError14from jinja2.ext import Extension15from jinja2.lexer import count_newlines16from jinja2.lexer import Token6from jinja import contextfunction7from jinja import DictLoader8from jinja import Environment9from jinja import nodes10from jinja._compat import BytesIO11from jinja._compat import itervalues12from jinja._compat import text_type13from jinja.exceptions import TemplateAssertionError14from jinja.ext import Extension15from jinja.lexer import count_newlines16from jinja.lexer import Token1718importable_object = 231920_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)
58 unmodified lines
79 return languages.get(language, {}).get(p, p)80 return languages.get(language, {}).get(s, s)818283i18n_env = Environment(84 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]85)83i18n_env = Environment(loader=DictLoader(i18n_templates), extensions=["jinja.ext.i18n"])84i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})87i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])85i18n_env_trimmed = Environment(extensions=["jinja.ext.i18n"])86i18n_env_trimmed.policies["ext.i18n.trimmed"] = True87i18n_env_trimmed.globals.update(88 {"_": gettext, "gettext": gettext, "ngettext": ngettext}89)9091newstyle_i18n_env = Environment(94 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]92 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja.ext.i18n"]93)94newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)9596
71 unmodified lines
168@pytest.mark.ext169class TestExtensions(object):170 def test_extend_late(self):171 env = Environment()174 env.add_extension("jinja2.ext.autoescape")172 env.add_extension("jinja.ext.autoescape")173 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')174 assert t.render() == "&lt;test&gt;"175176 def test_loop_controls(self):179 env = Environment(extensions=["jinja2.ext.loopcontrols"])177 env = Environment(extensions=["jinja.ext.loopcontrols"])178179 tmpl = env.from_string(180 """181 {%- for item in [1, 2, 3, 4] %}
12 unmodified lines
194 )195 assert tmpl.render() == "12"196197 def test_do(self):200 env = Environment(extensions=["jinja2.ext.do"])198 env = Environment(extensions=["jinja.ext.do"])199 tmpl = env.from_string(200 """201 {%- set items = [] %}202 {%- for char in "foo" %}
53 unmodified lines
256 assert ext[0].__class__ is T1257 assert ext[1].__class__ is T2258259 def test_debug(self):262 env = Environment(extensions=["jinja2.ext.debug"])260 env = Environment(extensions=["jinja.ext.debug"])261 t = env.from_string("Hello\n{% debug %}\nGoodbye")262 out = t.render()263264 for value in ("context", "cycler", "filters", "abs", "tests", "!="):
71 unmodified lines
336 )337 assert tmpl.render() == " hello\n world "338339 def test_extract(self):342 from jinja2.ext import babel_extract340 from jinja.ext import babel_extract341342 source = BytesIO(343 """344 {{ gettext('Hello World') }}
9 unmodified lines
354 (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),355 ]356357 def test_extract_trimmed(self):360 from jinja2.ext import babel_extract358 from jinja.ext import babel_extract359360 source = BytesIO(361 """362 {{ gettext(' Hello \n World') }}
10 unmodified lines
373 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),374 ]375376 def test_extract_trimmed_option(self):379 from jinja2.ext import babel_extract377 from jinja.ext import babel_extract378379 source = BytesIO(380 """381 {{ gettext(' Hello \n World') }}
11 unmodified lines
393 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),394 ]395396 def test_comment_extract(self):399 from jinja2.ext import babel_extract397 from jinja.ext import babel_extract398399 source = BytesIO(400 """401 {# trans first #}
80 unmodified lines
482 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"483 assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"484485 def test_autoescape_support(self):488 env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])486 env = Environment(extensions=["jinja.ext.autoescape", "jinja.ext.i18n"])487 env.install_gettext_callables(488 lambda x: u"<strong>Wert: %(name)s</strong>",489 lambda s, p, n: s,490 newstyle=True,
5 unmodified lines
496 assert t.render(ae=True) == "<strong>Wert: &lt;test&gt;</strong>"497 assert t.render(ae=False) == "<strong>Wert: <test></strong>"498499 def test_autoescape_macros(self):502 env = Environment(autoescape=False, extensions=["jinja2.ext.autoescape"])500 env = Environment(autoescape=False, extensions=["jinja.ext.autoescape"])501 template = (502 "{% macro m() %}<html>{% endmacro %}"503 "{% autoescape true %}{{ m() }}{% endautoescape %}"504 )
39 unmodified lines
544545@pytest.mark.ext546class TestAutoEscape(object):547 def test_scoped_setting(self):550 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)548 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)549 tmpl = env.from_string(550 """551 {{ "<HelloWorld>" }}552 {% autoescape false %}
7 unmodified lines
560 u"<HelloWorld>",561 u"&lt;HelloWorld&gt;",562 ]563566 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)564 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=False)565 tmpl = env.from_string(566 """567 {{ "<HelloWorld>" }}568 {% autoescape true %}
8 unmodified lines
577 u"<HelloWorld>",578 ]579580 def test_nonvolatile(self):583 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)581 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)582 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')583 assert tmpl.render() == ' foo="&lt;test&gt;"'584 tmpl = env.from_string(585 '{% autoescape false %}{{ {"foo": "<test>"}'
1 unmodified line
587 )588 assert tmpl.render() == " foo=&#34;&amp;lt;test&amp;gt;&#34;"589590 def test_volatile(self):593 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)591 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)592 tmpl = env.from_string(593 '{% autoescape foo %}{{ {"foo": "<test>"}'594 "|xmlattr|escape }}{% endautoescape %}"595 )596 assert tmpl.render(foo=False) == " foo=&#34;&amp;lt;test&amp;gt;&#34;"597 assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'598599 def test_scoping(self):602 env = Environment(extensions=["jinja2.ext.autoescape"])600 env = Environment(extensions=["jinja.ext.autoescape"])601 tmpl = env.from_string(602 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'603 '{% endautoescape %}{{ x }}{{ "<y>" }}'604 )605 assert tmpl.render(x=1) == "&lt;x&gt;1<y>"606607 def test_volatile_scoping(self):610 env = Environment(extensions=["jinja2.ext.autoescape"])608 env = Environment(extensions=["jinja.ext.autoescape"])609 tmplsource = """610 {% autoescape val %}611 {% macro foo(x) %}612 [{{ x }}]
7 unmodified lines
620 assert tmpl.render(val=False).split()[0] == text_type.__name__621622 # looking at the source we should see <testing> there in raw623 # (and then escaped as well)626 env = Environment(extensions=["jinja2.ext.autoescape"])624 env = Environment(extensions=["jinja.ext.autoescape"])625 pysource = env.compile(tmplsource, raw=True)626 assert "<testing>\\n" in pysource627630 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)628 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)629 pysource = env.compile(tmplsource, raw=True)630 assert "&lt;testing&gt;\\n" in pysource631632 def test_overlay_scopes(self):
26 unmodified lines
modified:tests/test_features.py+4 added-4 removed
1import sys23import pytest45from jinja2 import contextfilter6from jinja2 import Environment7from jinja2 import Template8from jinja2._compat import text_type5from jinja import contextfilter6from jinja import Environment7from jinja import Template8from jinja._compat import text_type91011@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")12def test_generator_stop():
30 unmodified lines
modified:tests/test_filters.py+4 added-4 removed
2 unmodified lines
3from collections import namedtuple45import pytest67from jinja2 import Environment8from jinja2 import Markup9from jinja2._compat import implements_to_string10from jinja2._compat import text_type7from jinja import Environment8from jinja import Markup9from jinja._compat import implements_to_string10from jinja._compat import text_type111213@implements_to_string14class Magic(object):
731 unmodified lines
modified:tests/test_idtracking.py+2 added-2 removed
1from jinja2 import nodes2from jinja2.idtracking import symbols_for_node1from jinja import nodes2from jinja.idtracking import symbols_for_node345def test_basics():6 for_loop = nodes.For(
283 unmodified lines
modified:tests/test_imports.py+5 added-5 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2.exceptions import TemplateNotFound7from jinja2.exceptions import TemplatesNotFound8from jinja2.exceptions import TemplateSyntaxError4from jinja import DictLoader5from jinja import Environment6from jinja.exceptions import TemplateNotFound7from jinja.exceptions import TemplatesNotFound8from jinja.exceptions import TemplateSyntaxError91011@pytest.fixture12def test_env():
167 unmodified lines
modified:tests/test_inheritance.py+3 added-3 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2 import TemplateRuntimeError4from jinja import DictLoader5from jinja import Environment6from jinja import TemplateRuntimeError78LAYOUTTEMPLATE = """\9|{% block block1 %}block 1 from layout{% endblock %}10|{% block block2 %}block 2 from layout{% endblock %}
277 unmodified lines
modified:tests/test_lexnparse.py+14 added-14 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import nodes6from jinja2 import Template7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError9from jinja2._compat import iteritems10from jinja2._compat import PY211from jinja2._compat import text_type12from jinja2.lexer import Token13from jinja2.lexer import TOKEN_BLOCK_BEGIN14from jinja2.lexer import TOKEN_BLOCK_END15from jinja2.lexer import TOKEN_EOF16from jinja2.lexer import TokenStream4from jinja import Environment5from jinja import nodes6from jinja import Template7from jinja import TemplateSyntaxError8from jinja import UndefinedError9from jinja._compat import iteritems10from jinja._compat import PY211from jinja._compat import text_type12from jinja.lexer import Token13from jinja.lexer import TOKEN_BLOCK_BEGIN14from jinja.lexer import TOKEN_BLOCK_END15from jinja.lexer import TOKEN_EOF16from jinja.lexer import TokenStream171819# how does a string look like in jinja syntax?20if PY2:
100 unmodified lines
121 tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")122 assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")123124 def test_operators(self, env):125 from jinja2.lexer import operators125 from jinja.lexer import operators126127 for test, expect in iteritems(operators):128 if test in "([{}])":129 continue
701 unmodified lines
modified:tests/test_loader.py+7 added-7 removed
6 unmodified lines
7import weakref89import pytest1011from jinja2 import Environment12from jinja2 import loaders13from jinja2 import PackageLoader14from jinja2._compat import PY215from jinja2._compat import PYPY16from jinja2.exceptions import TemplateNotFound17from jinja2.loaders import split_template_path11from jinja import Environment12from jinja import loaders13from jinja import PackageLoader14from jinja._compat import PY215from jinja._compat import PYPY16from jinja.exceptions import TemplateNotFound17from jinja.loaders import split_template_path181920@pytest.mark.loaders21class TestLoaders(object):
356 unmodified lines
modified:tests/test_nativetypes.py+5 added-5 removed
1import pytest23from jinja2._compat import text_type4from jinja2.exceptions import UndefinedError5from jinja2.nativetypes import NativeEnvironment6from jinja2.nativetypes import NativeTemplate7from jinja2.runtime import Undefined3from jinja._compat import text_type4from jinja.exceptions import UndefinedError5from jinja.nativetypes import NativeEnvironment6from jinja.nativetypes import NativeTemplate7from jinja.runtime import Undefined8910@pytest.fixture11def env():
128 unmodified lines
modified:tests/test_regression.py+15 added-15 removed
1 unmodified line
2import sys34import pytest56from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import PrefixLoader9from jinja2 import Template10from jinja2 import TemplateAssertionError11from jinja2 import TemplateNotFound12from jinja2 import TemplateSyntaxError13from jinja2._compat import text_type6from jinja import DictLoader7from jinja import Environment8from jinja import PrefixLoader9from jinja import Template10from jinja import TemplateAssertionError11from jinja import TemplateNotFound12from jinja import TemplateSyntaxError13from jinja._compat import text_type141516@pytest.mark.regression17class TestCorner(object):
276 unmodified lines
294295 assert e.value.name == "foo/bar.html"296297 def test_contextfunction_callable_classes(self, env):298 from jinja2.utils import contextfunction298 from jinja.utils import contextfunction299300 class CallableClass(object):301 @contextfunction302 def __call__(self, ctx):
65 unmodified lines
368 assert t.render().strip() == "45|6"369370 def test_macro_escaping(self):371 env = Environment(372 autoescape=lambda x: False, extensions=["jinja2.ext.autoescape"]372 autoescape=lambda x: False, extensions=["jinja.ext.autoescape"]373 )374 template = "{% macro m() %}<html>{% endmacro %}"375 template += "{% autoescape true %}{{ m() }}{% endautoescape %}"376 assert env.from_string(template).render()
199 unmodified lines
576 )577 assert env.get_template("main").render() == "123"578579 def test_grouper_repr(self):580 from jinja2.filters import _GroupTuple580 from jinja.filters import _GroupTuple581582 t = _GroupTuple("foo", [1, 2])583 assert t.grouper == "foo"584 assert t.list == [1, 2]585 assert repr(t) == "('foo', [1, 2])"586 assert str(t) == "('foo', [1, 2])"587588 def test_custom_context(self, env):589 from jinja2.runtime import Context589 from jinja.runtime import Context590591 class MyContext(Context):592 pass593
4 unmodified lines
598 env = MyEnvironment(loader=loader)599 assert env.get_template("test").render(foobar="test") == "test"600601 def test_legacy_custom_context(self, env):602 from jinja2.runtime import Context, missing602 from jinja.runtime import Context, missing603604 class MyContext(Context):605 def resolve(self, name):606 if name == "foo":
12 unmodified lines
619 )620 assert tmpl.render(values=[]) == "0"621622 def test_markup_and_chainable_undefined(self):623 from jinja2 import Markup624 from jinja2.runtime import ChainableUndefined623 from jinja import Markup624 from jinja.runtime import ChainableUndefined625626 assert str(Markup(ChainableUndefined())) == ""
modified:tests/test_runtime.py+2 added-2 removed
1import itertools23from jinja2 import Template4from jinja2.runtime import LoopContext3from jinja import Template4from jinja.runtime import LoopContext56TEST_IDX_TEMPLATE_STR_1 = (7 "[{% for i in lst|reverse %}(len={{ loop.length }},"8 " revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }}){% endfor %}]"
48 unmodified lines
modified:tests/test_security.py+11 added-11 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import escape6from jinja2 import Markup7from jinja2._compat import text_type8from jinja2.exceptions import SecurityError9from jinja2.exceptions import TemplateRuntimeError10from jinja2.exceptions import TemplateSyntaxError11from jinja2.nodes import EvalContext12from jinja2.sandbox import ImmutableSandboxedEnvironment13from jinja2.sandbox import SandboxedEnvironment14from jinja2.sandbox import unsafe4from jinja import Environment5from jinja import escape6from jinja import Markup7from jinja._compat import text_type8from jinja.exceptions import SecurityError9from jinja.exceptions import TemplateRuntimeError10from jinja.exceptions import TemplateSyntaxError11from jinja.nodes import EvalContext12from jinja.sandbox import ImmutableSandboxedEnvironment13from jinja.sandbox import SandboxedEnvironment14from jinja.sandbox import unsafe151617class PrivateStuff(object):18 def bar(self):
195 unmodified lines
modified:tests/test_tests.py+2 added-2 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import Markup4from jinja import Environment5from jinja import Markup678class MyDict(dict):9 pass
201 unmodified lines
modified:tests/test_utils.py+9 added-9 removed
5 unmodified lines
67import pytest8from markupsafe import Markup910from jinja2._compat import range_type11from jinja2._compat import string_types12from jinja2.utils import consume13from jinja2.utils import generate_lorem_ipsum14from jinja2.utils import LRUCache15from jinja2.utils import missing16from jinja2.utils import object_type_repr17from jinja2.utils import select_autoescape18from jinja2.utils import urlize10from jinja._compat import range_type11from jinja._compat import string_types12from jinja.utils import consume13from jinja.utils import generate_lorem_ipsum14from jinja.utils import LRUCache15from jinja.utils import missing16from jinja.utils import object_type_repr17from jinja.utils import select_autoescape18from jinja.utils import urlize192021@pytest.mark.utils22@pytest.mark.lrucache
186 unmodified lines
modified:CHANGES.rst+8 added-13 removed
18 unmodified lines
19 legibility, like 12_345. :pr:`923`20- Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`21- The ``trim`` filter takes an optional string of characters to trim.22 :pr:`828`23- A new ``jinja2.ext.debug`` extension adds a ``{% debug %}`` tag to23- A new ``jinja.ext.debug`` extension adds a ``{% debug %}`` tag to24 quickly dump the current context and available filters and tests.25 :issue:`174`, :pr:`798, 983`26- Lexing templates with large amounts of whitespace is much faster.27 :issue:`857`, :pr:`858`
335 unmodified lines
363- Added a check for default arguments followed by non-default364 arguments. This change makes ``{% macro m(x, y=1, z) %}`` a syntax365 error. The previous behavior for this code was broken anyway366 (resulting in the default value being applied to ``y``).367- Add ability to use custom subclasses of368 ``jinja2.compiler.CodeGenerator`` and ``jinja2.runtime.Context`` by369 adding two new attributes to the environment370 (``code_generator_class`` and ``context_class``) (pull request371 ``:issue:`404```).367- Add ability to use custom subclasses of ``CodeGenerator`` and368 ``Context`` by adding two new attributes to the environment369 (``code_generator_class`` and ``context_class``). :pr:`404`370- Added support for context/environment/evalctx decorator functions on371 the finalize callback of the environment.372- Escape query strings for urlencode properly. Previously slashes were373 not escaped in that place.
182 unmodified lines
556 time) by adding support for case insensitive searches.557- Fixed a bug for getattribute constant folding.558- Support for newstyle gettext translations which result in a nicer559 in-template user interface and more consistent catalogs.562 (:ref:`newstyle-gettext`)560- It's now possible to register extensions after an environment was561 created.562563
19 unmodified lines
583 compile the templates from a configured loader into a zip file or584 folder.585- The _speedups C extension now supports Python 3.586- Added support for autoescaping toggling sections and support for590 evaluation contexts (:ref:`eval-context`).587 evaluation contexts.588- Extensions have a priority now.589590591Version 2.3.1
93 unmodified lines
685 part of a visible area.686- Added ``sort`` filter that works like ``dictsort`` but for arbitrary687 sequences.688- Fixed a bug with empty statements in macros.692- Implemented a bytecode cache system. (:ref:`bytecode-cache`)689- Implemented a bytecode cache system.690- The template context is now weakref-able691- Inclusions and imports "with context" forward all variables now, not692 only the initial context.693- Added a cycle helper called ``cycler``.
11 unmodified lines
705- The subscribing of objects (looking up attributes and items) changed706 from slightly. It's now possible to give attributes or items a707 higher priority by either using dot-notation lookup or the bracket708 syntax. This also changed the AST slightly. ``Subscript`` is gone712 and was replaced with :class:`~jinja2.nodes.Getitem` and713 :class:`~jinja2.nodes.Getattr`. For more information see :ref:`the714 implementation details <notes-on-subscriptions>`.709 and was replaced with ``Getitem`` and ``Getattr``.710- Added support for preprocessing and token stream filtering for711 extensions. This would allow extensions to allow simplified gettext712 calls in template data and something similar.718- Added :meth:`jinja2.environment.TemplateStream.dump`.713- Added ``TemplateStream.dump``.714- Added missing support for implicit string literal concatenation.715 ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}``716- ``else`` is optional for conditional expressions. If not given it717 evaluates to ``false``.
13 unmodified lines
modified:README.rst+2 added-2 removed
31 unmodified lines
32Install and update using `pip`_:3334.. code-block:: text3536 $ pip install -U Jinja236 $ pip install -U Jinja3738.. _pip: https://pip.pypa.io/en/stable/quickstart/3940
17 unmodified lines
58-----5960- Website: https://palletsprojects.com/p/jinja/61- Documentation: https://jinja.palletsprojects.com/62- Releases: https://pypi.org/project/Jinja2/62- Releases: https://pypi.org/project/Jinja/63- Code: https://github.com/pallets/jinja64- Issue tracker: https://github.com/pallets/jinja/issues65- Test status: https://dev.azure.com/pallets/jinja/_build66- Official chat: https://discord.gg/t6rrQZH
modified:setup.cfg+6 added-6 removed
6 unmodified lines
7[tool:pytest]8testpaths = tests9filterwarnings =10 error11 ignore:the sets module:DeprecationWarning:jinja2.sandbox11 ignore:the sets module:DeprecationWarning:jinja.sandbox1213[coverage:run]14branch = True15source =16 jinja216 jinja17 tests1819[coverage:paths]20source =21 src/jinja222 .tox/*/lib/python*/site-packages/jinja223 .tox/*/site-packages/jinja221 src/jinja22 .tox/*/lib/python*/site-packages/jinja23 .tox/*/site-packages/jinja2425[flake8]26# B = bugbear27# E = pycodestyle errors
13 unmodified lines
41# up to 88 allowed by bugbear B95042max-line-length = 8043per-file-ignores =44 # __init__ module exports names45 src/jinja2/__init__.py: F40145 src/jinja/__init__.py: F401
modified:setup.py+3 added-3 removed
5 unmodified lines
67with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()910with io.open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:10with io.open("src/jinja/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)1213setup(14 name="Jinja2",14 name="Jinja",15 version=version,16 url="https://palletsprojects.com/p/jinja/",17 project_urls={18 "Documentation": "https://jinja.palletsprojects.com/",
31 unmodified lines
50 include_package_data=True,51 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",52 install_requires=["MarkupSafe>=0.23"],53 extras_require={"i18n": ["Babel>=0.8"]},54 entry_points={"babel.extractors": ["jinja2 = jinja2.ext:babel_extract[i18n]"]},54 entry_points={"babel.extractors": ["jinja = jinja.ext:babel_extract[i18n]"]},55)