Skip to content
Myr

Merge branch 'master' into 857-lexer-whitespace-performance

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

authored by David Lord · committed by GitHub · parents 7d00a40, 381d72a · Browse files · 69 files+1688 added−2072 removed
This commit

State

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

Diff stats

69 files+1688 added−2072 removed

  • tests:+369 added−40 removed
  • other:+1319 added−2032 removed

69 files+1688 added−2072 removed

deleted:docs/_build/.ignore
deleted:docs/_static/.ignore
added:docs/_static/jinja-logo-sidebar.pngbinary

A binary file, added.

added:docs/_static/jinja-logo.pngbinary

A binary file, added.

deleted:docs/_static/jinja-small.pngbinary

A binary file, deleted.

deleted:docs/_templates/sidebarintro.html-20 removed
deleted:docs/_templates/sidebarlogo.html-3 removed
deleted:docs/_themes/jinja/static/jinja.css_t-396 removed
1/*2 * jinja.css_t3 * ~~~~~~~~~~~4 *5 * :copyright: Copyright 2011 by Armin Ronacher.6 * :license: Flask Design License, see LICENSE for details.7 */89@import url(http://fonts.googleapis.com/css?family=Crimson+Text);1011{% set page_width = '940px' %}12{% set sidebar_width = '220px' %}13{% set font_family = 'Georgia, serif' %}14{% set header_font_family = 'Crimson Text, ' ~ font_family %}1516@import url("basic.css");1718/* -- page layout ----------------------------------------------------------- */1920body {21 font-family: {{ font_family }};22 font-size: 17px;23 background-color: white;24 color: #000;25 margin: 0;26 padding: 0;27}2829div.document {30 width: {{ page_width }};31 margin: 30px auto 0 auto;32}3334div.documentwrapper {35 float: left;36 width: 100%;37}3839div.bodywrapper {40 margin: 0 0 0 {{ sidebar_width }};41}4243div.sphinxsidebar {44 width: {{ sidebar_width }};45}4647hr {48 border: 1px solid #B1B4B6;49}5051div.body {52 background-color: #ffffff;53 color: #3E4349;54 padding: 0 30px 0 30px;55}5657img.floatingflask {58 padding: 0 0 10px 10px;59 float: right;60}6162div.footer {63 width: {{ page_width }};64 margin: 20px auto 30px auto;65 font-size: 14px;66 color: #888;67 text-align: right;68}6970div.footer a {71 color: #888;72}7374div.related {75 display: none;76}7778div.sphinxsidebar a {79 color: #444;80 text-decoration: none;81 border-bottom: 1px dotted #999;82}8384div.sphinxsidebar a:hover {85 border-bottom: 1px solid #999;86}8788div.sphinxsidebar {89 font-size: 15px;90 line-height: 1.5;91}9293div.sphinxsidebarwrapper {94 padding: 18px 10px;95}9697div.sphinxsidebarwrapper p.logo {98 padding: 0 0 20px 0;99 margin: 0;100 text-align: center;101}102103div.sphinxsidebar h3,104div.sphinxsidebar h4 {105 font-family: {{ font_family }};106 color: #444;107 font-size: 24px;108 font-weight: normal;109 margin: 0 0 5px 0;110 padding: 0;111}112113div.sphinxsidebar h4 {114 font-size: 20px;115}116117div.sphinxsidebar h3 a {118 color: #444;119}120121div.sphinxsidebar p.logo a,122div.sphinxsidebar h3 a,123div.sphinxsidebar p.logo a:hover,124div.sphinxsidebar h3 a:hover {125 border: none;126}127128div.sphinxsidebar p {129 color: #555;130 margin: 10px 0;131}132133div.sphinxsidebar ul {134 margin: 10px 0;135 padding: 0;136 color: #000;137}138139div.sphinxsidebar input {140 border: 1px solid #ccc;141 font-family: {{ font_family }};142 font-size: 14px;143}144145div.sphinxsidebar form.search input[name="q"] {146 width: 130px;147}148149/* -- body styles ----------------------------------------------------------- */150151a {152 color: #aa0000;153 text-decoration: underline;154}155156a:hover {157 color: #dd0000;158 text-decoration: underline;159}160161div.body h1,162div.body h2,163div.body h3,164div.body h4,165div.body h5,166div.body h6 {167 font-family: {{ header_font_family }};168 font-weight: normal;169 margin: 30px 0px 10px 0px;170 padding: 0;171 color: black;172}173174div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }175div.body h2 { font-size: 180%; }176div.body h3 { font-size: 150%; }177div.body h4 { font-size: 130%; }178div.body h5 { font-size: 100%; }179div.body h6 { font-size: 100%; }180181a.headerlink {182 color: #ddd;183 padding: 0 4px;184 text-decoration: none;185}186187a.headerlink:hover {188 color: #444;189 background: #eaeaea;190}191192div.body p, div.body dd, div.body li {193 line-height: 1.4em;194}195196div.admonition {197 background: #fafafa;198 margin: 20px -30px;199 padding: 10px 30px;200 border-top: 1px solid #ccc;201 border-bottom: 1px solid #ccc;202}203204div.admonition tt.xref, div.admonition a tt {205 border-bottom: 1px solid #fafafa;206}207208dd div.admonition {209 margin-left: -60px;210 padding-left: 60px;211}212213div.admonition p.admonition-title {214 font-family: {{ font_family }};215 font-weight: normal;216 font-size: 24px;217 margin: 0 0 10px 0;218 padding: 0;219 line-height: 1;220}221222div.admonition p.last {223 margin-bottom: 0;224}225226div.highlight {227 background-color: white;228}229230dt:target, .highlight {231 background: #FAF3E8;232}233234div.note {235 background-color: #eee;236 border: 1px solid #ccc;237}238239div.seealso {240 background-color: #ffc;241 border: 1px solid #ff6;242}243244div.topic {245 background-color: #eee;246}247248p.admonition-title {249 display: inline;250}251252p.admonition-title:after {253 content: ":";254}255256pre, tt {257 font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;258 font-size: 0.85em;259}260261img.screenshot {262}263264tt.descname, tt.descclassname {265 font-size: 0.95em;266}267268tt.descname {269 padding-right: 0.08em;270}271272img.screenshot {273 -moz-box-shadow: 2px 2px 4px #eee;274 -webkit-box-shadow: 2px 2px 4px #eee;275 box-shadow: 2px 2px 4px #eee;276}277278table.docutils {279 border: 1px solid #888;280 -moz-box-shadow: 2px 2px 4px #eee;281 -webkit-box-shadow: 2px 2px 4px #eee;282 box-shadow: 2px 2px 4px #eee;283}284285table.docutils td, table.docutils th {286 border: 1px solid #888;287 padding: 0.25em 0.7em;288}289290table.field-list, table.footnote {291 border: none;292 -moz-box-shadow: none;293 -webkit-box-shadow: none;294 box-shadow: none;295}296297table.footnote {298 margin: 15px 0;299 width: 100%;300 border: 1px solid #eee;301 background: #fdfdfd;302 font-size: 0.9em;303}304305table.footnote + table.footnote {306 margin-top: -15px;307 border-top: none;308}309310table.field-list th {311 padding: 0 0.8em 0 0;312}313314table.field-list td {315 padding: 0;316}317318table.footnote td.label {319 width: 0px;320 padding: 0.3em 0 0.3em 0.5em;321}322323table.footnote td {324 padding: 0.3em 0.5em;325}326327dl {328 margin: 0;329 padding: 0;330}331332dl dd {333 margin-left: 30px;334}335336blockquote {337 margin: 0 0 0 30px;338 padding: 0;339}340341ul, ol {342 margin: 10px 0 10px 30px;343 padding: 0;344}345346pre {347 background: #eee;348 padding: 7px 30px;349 margin: 15px -30px;350 line-height: 1.3em;351}352353dl pre, blockquote pre, li pre {354 margin-left: -60px;355 padding-left: 60px;356}357358dl dl pre {359 margin-left: -90px;360 padding-left: 90px;361}362363tt {364 background-color: #E8EFF0;365 color: #222;366 /* padding: 1px 2px; */367}368369tt.xref, a tt {370 background-color: #E8EFF0;371 border-bottom: 1px solid white;372}373374a.reference {375 text-decoration: none;376 border-bottom: 1px dotted #bb0000;377}378379a.reference:hover {380 border-bottom: 1px solid #dd0000;381}382383a.footnote-reference {384 text-decoration: none;385 font-size: 0.7em;386 vertical-align: top;387 border-bottom: 1px dotted #bb0000;388}389390a.footnote-reference:hover {391 border-bottom: 1px solid #dd0000;392}393394a:hover tt {395 background: #EEE;396}
deleted:docs/_themes/jinja/layout.html-8 removed
deleted:docs/_themes/jinja/relations.html-19 removed
deleted:docs/_themes/jinja/theme.conf-3 removed
1[theme]2inherit = basic3stylesheet = jinja.css
deleted:docs/_themes/LICENSE-37 removed
1Copyright (c) 2010 by Armin Ronacher.23Some rights reserved.45Redistribution and use in source and binary forms of the theme, with or6without modification, are permitted provided that the following conditions7are met:89* Redistributions of source code must retain the above copyright10 notice, this list of conditions and the following disclaimer.1112* Redistributions in binary form must reproduce the above13 copyright notice, this list of conditions and the following14 disclaimer in the documentation and/or other materials provided15 with the distribution.1617* The names of the contributors may not be used to endorse or18 promote products derived from this software without specific19 prior written permission.2021We kindly ask you to only use these themes in an unmodified manner just22for Flask and Flask-related products, not for unrelated projects. If you23like the visual style and want to use it for your own projects, please24consider making some larger changes to the themes (such as changing25font faces, sizes, colors or margins).2627THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"28AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE29IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE30ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE31LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR32CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF33SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS34INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN35CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)36ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE37POSSIBILITY OF SUCH DAMAGE.
deleted:docs/_themes/README-31 removed
1Flask Sphinx Styles2===================34This repository contains sphinx styles for Flask and Flask related5projects. To use this style in your Sphinx documentation, follow6this guide:781. put this folder as _themes into your docs folder. Alternatively9 you can also use git submodules to check out the contents there.102. add this to your conf.py:1112 sys.path.append(os.path.abspath('_themes'))13 html_theme_path = ['_themes']14 html_theme = 'flask'1516The following themes exist:1718- 'flask' - the standard flask documentation theme for large19 projects20- 'flask_small' - small one-page theme. Intended to be used by21 very small addon libraries for flask.2223The following options exist for the flask_small theme:2425 [options]26 index_logo = '' filename of a picture in _static27 to be used as replacement for the28 h1 in the index.rst file.29 index_logo_height = 120px height of the index logo30 github_fork = '' repository name on github for the31 "fork me" badge
modified:docs/api.rst+7 added-4 removed
1API2===34.. module:: jinja25 :noindex:6 :synopsis: public Jinja2 API78This document describes the API to Jinja2 and not the template language. It9will be most useful as reference to those implementing the template interface
36 unmodified lines
46 template = env.get_template('mytemplate.html')4748To render it with some variables, just call the :meth:`render` method::4949 print template.render(the='variables', go='here')50 print(template.render(the='variables', go='here'))5152Using a template loader rather than passing strings to :class:`Template`53or :meth:`Environment.from_string` has multiple advantages. Besides being54a lot easier to use it also enables template inheritance.
59 unmodified lines
114>>> m.b115u'f\xf6\xf6'116117117.. _Unicode documentation: https://docs.python.org/dev/howto/unicode.html118.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html119120High Level API121--------------122
199 unmodified lines
322unable to look up a name or access an attribute one of those objects is323created and returned. Some operations on undefined values are then allowed,324others fail.325325The closest to regular Python behavior is the `StrictUndefined` which326The closest to regular Python behavior is the :class:`StrictUndefined` which327disallows all operations beside testing if it's an undefined object.328329.. autoclass:: jinja2.Undefined()330
22 unmodified lines
353 When called with any arguments this method raises354 :attr:`_undefined_exception` with an error message generated355 from the undefined hints stored on the undefined object.356357.. autoclass:: jinja2.ChainableUndefined()358359.. autoclass:: jinja2.DebugUndefined()360361.. autoclass:: jinja2.StrictUndefined()362
473 unmodified lines
836837 def is_prime(n):838 if n == 2:839 return True837 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):840 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):841 if n % i == 0:842 return False843 return True844
91 unmodified lines
modified:docs/cache_extension.py+1 added-1 removed
2 unmodified lines
345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.7 tags = set(['cache'])7 tags = {'cache'}89 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)11
45 unmodified lines
modified:docs/changelog.rst+2 added-1 removed
1.. module:: jinja21Changelog2=========34.. include:: ../CHANGES.rst
modified:docs/conf.py+42 added-150 removed
1# -*- coding: utf-8 -*-2#3# Jinja2 documentation build configuration file, created by4# sphinx-quickstart on Sun Apr 27 21:42:41 2008.5#6# This file is execfile()d with the current directory set to its containing dir.7#8# The contents of this file are pickled, so don't put values in the namespace9# that aren't pickleable (module imports are okay, they're removed automatically).10#11# All configuration values have a default value; values that are commented out12# serve to show the default value.1from pallets_sphinx_themes import get_version2from pallets_sphinx_themes import ProjectLink314import sys, os4# Project --------------------------------------------------------------516# If your extensions are in another directory, add it here. If the directory17# is relative to the documentation root, use os.path.abspath to make it18# absolute, like shown here.19sys.path.append(os.path.dirname(os.path.abspath(__file__)))6project = "Jinja"7copyright = "2007 Pallets"8author = "Pallets"9release, version = get_version("Jinja2")1021# General configuration22# ---------------------11# General --------------------------------------------------------------1224# Add any Sphinx extension module names here, as strings. They can be extensions25# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.26extensions = ['sphinx.ext.autodoc', 'jinjaext']2728# Add any paths that contain templates here, relative to this directory.29templates_path = ['_templates']3031# The suffix of source filenames.32source_suffix = '.rst'3334# The master toctree document.35master_doc = 'index'3637# General substitutions.38project = 'Jinja2'39copyright = '2008, Armin Ronacher'4041# The default replacements for |version| and |release|, also used in various42# other places throughout the built documents.43#44# The short X.Y version.45import pkg_resources46try:47 release = pkg_resources.get_distribution('Jinja2').version48except ImportError:49 print 'To build the documentation, The distribution information of Jinja2'50 print 'Has to be available. Either install the package into your'51 print 'development environment or run "setup.py develop" to setup the'52 print 'metadata. A virtualenv is recommended!'53 sys.exit(1)54if 'dev' in release:55 release = release.split('dev')[0] + 'dev'56version = '.'.join(release.split('.')[:2])5758# There are two options for replacing |today|: either, you set today to some59# non-false value, then it is used:60#today = ''61# Else, today_fmt is used as the format for a strftime call.62today_fmt = '%B %d, %Y'6364# List of documents that shouldn't be included in the build.65#unused_docs = []6667# If true, '()' will be appended to :func: etc. cross-reference text.68#add_function_parentheses = True6970# If true, the current module name will be prepended to all description71# unit titles (such as .. function::).72#add_module_names = True7374# If true, sectionauthor and moduleauthor directives will be shown in the75# output. They are ignored by default.76#show_authors = False7778# The name of the Pygments (syntax highlighting) style to use.79pygments_style = 'jinjaext.JinjaStyle'808182# Options for HTML output83# -----------------------8485html_theme = 'jinja'86html_theme_path = ['_themes']8788# The name for this set of Sphinx documents. If None, it defaults to89# "<project> v<release> documentation".90#html_title = None9192# Add any paths that contain custom static files (such as style sheets) here,93# relative to this directory. They are copied after the builtin static files,94# so a file named "default.css" will overwrite the builtin "default.css".95html_static_path = ['_static']9697# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,98# using the given strftime format.99html_last_updated_fmt = '%b %d, %Y'100101# If true, SmartyPants will be used to convert quotes and dashes to102# typographically correct entities.103#html_use_smartypants = True104105# no modindex106html_use_modindex = False107108# If true, the reST sources are included in the HTML build as _sources/<name>.109#html_copy_source = True110111# If true, an OpenSearch description file will be output, and all pages will112# contain a <link> tag referring to it.113#html_use_opensearch = False114115# Output file base name for HTML help builder.116htmlhelp_basename = 'Jinja2doc'117118119# Options for LaTeX output120# ------------------------121122# The paper size ('letter' or 'a4').123latex_paper_size = 'a4'124125# The font size ('10pt', '11pt' or '12pt').126#latex_font_size = '10pt'127128# Grouping the document tree into LaTeX files. List of tuples129# (source start file, target name, title, author, document class [howto/manual]).130latex_documents = [131 ('latexindex', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher',132 'manual'),13master_doc = "index"14extensions = [15 "sphinx.ext.autodoc",16 "sphinx.ext.intersphinx",17 "pallets_sphinx_themes",18 "sphinxcontrib.log_cabinet",19 "sphinx_issues",20]21intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}22issues_github_path = "pallets/jinja"23135# Additional stuff for LaTeX136latex_elements = {137 'fontpkg': r'\usepackage{mathpazo}',138 'papersize': 'a4paper',139 'pointsize': '12pt',140 'preamble': r'''141\usepackage{jinjastyle}24# HTML -----------------------------------------------------------------25143% i hate you latex144\DeclareUnicodeCharacter{14D}{o}145'''26html_theme = "jinja"27html_theme_options = {"index_sidebar_logo": False}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/"),33 ProjectLink("Source Code", "https://github.com/pallets/jinja/"),34 ProjectLink("Issue Tracker", "https://github.com/pallets/jinja/issues/"),35 ]36}147148latex_use_parts = True149150latex_additional_files = ['jinjastyle.sty', 'logo.pdf']151152# If false, no module index is generated.153latex_use_modindex = False15437html_sidebars = {156 'index': ['sidebarlogo.html', 'sidebarintro.html', 'sourcelink.html',157 'searchbox.html'],158 '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',159 'sourcelink.html', 'searchbox.html']38 "index": ["project.html", "localtoc.html", "searchbox.html"],39 "**": ["localtoc.html", "relations.html", "searchbox.html"],40}41singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}42html_static_path = ["_static"]43html_favicon = "_static/jinja-logo-sidebar.png"44html_logo = "_static/jinja-logo-sidebar.png"45html_title = "Jinja Documentation ({})".format(version)46html_show_sourcelink = False4748# LaTeX ----------------------------------------------------------------4950latex_documents = [51 (master_doc, "Jinja-{}.tex".format(version), html_title, author, "manual")52]
deleted:docs/contents.rst.inc-24 removed
1Jinja2 Documentation2--------------------34.. toctree::5 :maxdepth: 267 intro8 api9 sandbox10 nativetypes11 templates12 extensions13 integration14 switching15 tricks1617Additional Information18----------------------1920.. toctree::21 :maxdepth: 22223 faq24 changelog
modified:docs/extensions.rst+47 added-35 removed
12 unmodified lines
1314Extensions are added to the Jinja2 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:`Environment` constructor. The following17``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following18example creates a Jinja2 environment with the i18n extension loaded::1920 jinja_env = Environment(extensions=['jinja2.ext.i18n'])21
2 unmodified lines
2425i18n Extension26--------------2728**Import name:** `jinja2.ext.i18n`28**Import name:** ``jinja2.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or `babel`_. If31the i18n extension is enabled Jinja2 provides a `trans` statement that marks32the wrapped string as translatable and calls `gettext`.31the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32the wrapped string as translatable and calls ``gettext``.3334After enabling, dummy `_` function that forwards calls to `gettext` is added34After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35to the environment globals. An internationalized application then has to36provide a `gettext` function and optionally an `ngettext` function into the36provide a ``gettext`` function and optionally an ``ngettext`` function into the37namespace, either globally or for each rendering.3839Environment Methods40~~~~~~~~~~~~~~~~~~~
3 unmodified lines
4445.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4647 Installs a translation globally for that environment. The translations48 object provided must implement at least `ugettext` and `ungettext`.49 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes50 as well as `Babel`_\s `Translations` class are supported.48 object provided must implement at least ``ugettext`` and ``ungettext``.49 The ``gettext.NullTranslations`` and ``gettext.GNUTranslations`` classes50 as well as `Babel`_\s ``Translations`` class are supported.5152 .. versionchanged:: 2.5 newstyle gettext added5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)
5 unmodified lines
60 .. versionchanged:: 2.5 newstyle gettext added6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 Installs the given `gettext` and `ngettext` callables into the64 Installs the given ``gettext`` and ``ngettext`` callables into the65 environment as globals. They are supposed to behave exactly like the66 standard library's :func:`gettext.ugettext` and67 :func:`gettext.ungettext` functions.6869 If `newstyle` is activated, the callables are wrapped to work like69 If ``newstyle`` is activated, the callables are wrapped to work like70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.573
7 unmodified lines
8182 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:8485 * `lineno` is the number of the line on which the string was found,86 * `function` is the name of the `gettext` function used (if the85 * ``lineno`` is the number of the line on which the string was found,86 * ``function`` is the name of the ``gettext`` function used (if the87 string was extracted from embedded Python code), and88 * `message` is the string itself (a `unicode` object, or a tuple89 of `unicode` objects for functions with multiple string arguments).88 * ``message`` is the string itself (a ``unicode`` object, or a tuple89 of ``unicode`` objects for functions with multiple string arguments).9091 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92 can be used to extract strings for babel.93
5 unmodified lines
99 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])101 env.install_gettext_translations(translations)102103The `get_gettext_translations` function would return the translator for the104current configuration. (For example by using `gettext.find`)103The ``get_gettext_translations`` function would return the translator for the104current configuration. (For example by using ``gettext.find``)105106The usage of the `i18n` extension for template designers is covered as part106The usage of the ``i18n`` extension for template designers is covered as part107:ref:`of the template documentation <i18n-in-templates>`.108109.. _gettext: https://docs.python.org/dev/library/gettext109.. _gettext: https://docs.python.org/3/library/gettext.html110.. _Babel: http://babel.pocoo.org/111112.. _newstyle-gettext:113
53 unmodified lines
167168Expression Statement169--------------------170171**Import name:** `jinja2.ext.do`171**Import name:** ``jinja2.ext.do``172173The "do" aka expression-statement extension adds a simple `do` tag to the173The "do" aka expression-statement extension adds a simple ``do`` tag to the174template engine that works like a variable expression but ignores the175return value.176177.. _loopcontrols-extension:178179Loop Controls180-------------181182**Import name:** `jinja2.ext.loopcontrols`182**Import name:** ``jinja2.ext.loopcontrols``183184This extension adds support for `break` and `continue` in loops. After184This extension adds support for ``break`` and ``continue`` in loops. After185enabling, Jinja2 provides those two keywords which work exactly like in186Python.187188.. _with-extension:189190With Statement191--------------192193**Import name:** `jinja2.ext.with_`193**Import name:** ``jinja2.ext.with_``194195.. versionchanged:: 2.9196197This extension is now built-in and no longer does anything.197 This extension is now built-in and no longer does anything.198199.. _autoescape-extension:200201Autoescape Extension202--------------------203204**Import name:** `jinja2.ext.autoescape`204**Import name:** ``jinja2.ext.autoescape``205206.. versionchanged:: 2.9207208This extension was removed and is now built-in. Enabling the extension209no longer does anything.208 This extension was removed and is now built-in. Enabling the209 extension no longer does anything.210211212.. _debug-extension:213214Debug Extension215---------------216217**Import name:** ``jinja2.ext.debug``218219Adds a ``{% debug %}`` tag to dump the current context as well as the220available filters and tests. This is useful to see what's available to221use in the template without setting up a debugger.222223224.. _writing-extensions:225226Writing Extensions227------------------
14 unmodified lines
242243Example Extension244~~~~~~~~~~~~~~~~~245234The following example implements a `cache` tag for Jinja2 by using the235`Werkzeug`_ caching contrib module:246The following example implements a ``cache`` tag for Jinja2 by using the247`cachelib`_ library:248249.. literalinclude:: cache_extension.py250 :language: python251252And here is how you use it in an environment::253254 from jinja2 import Environment243 from werkzeug.contrib.cache import SimpleCache255 from cachelib import SimpleCache256257 env = Environment(extensions=[FragmentCacheExtension])258 env.fragment_cache = SimpleCache()259
7 unmodified lines
267 ...268 </div>269 {% endcache %}270259.. _Werkzeug: http://werkzeug.pocoo.org/271.. _cachelib: https://github.com/pallets/cachelib272273Extension API274~~~~~~~~~~~~~275
27 unmodified lines
303304 The filename of the template the parser processes. This is **not**305 the load name of the template. For the load name see :attr:`name`.306 For templates that were not loaded form the file system this is295 `None`.307 ``None``.308309 .. attribute:: name310311 The load name of the template.
18 unmodified lines
330331 .. attribute:: type332333 The type of the token. This string is interned so you may compare322 it with arbitrary strings using the `is` operator.334 it with arbitrary strings using the ``is`` operator.335336 .. attribute:: value337338 The value of the token.
17 unmodified lines
356For more information have a look at the repr of :meth:`jinja2.Environment.parse`.357358.. module:: jinja2.nodes359348.. jinjanodes::360.. jinja:nodes:: jinja2.nodes.Node361362.. autoexception:: Impossible
modified:docs/faq.rst+3 added-3 removed
24 unmodified lines
25speaking the performance of a template engine doesn't matter much as the26usual bottleneck in a web application is either the database or the application27code.2829.. _Mako: http://www.makotemplates.org/29.. _Mako: https://www.makotemplates.org/3031How Compatible is Jinja2 with Django?32-------------------------------------33
118 unmodified lines
152153Python 2.3 is missing a lot of features that are used heavily in Jinja2. This154decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155harder to maintain the code for older Python versions. If you really need156Python 2.3 support you either have to use `Jinja 1`_ or other templating156Python 2.3 support you either have to use Jinja 1 or other templating157engines that still support 2.3.158159Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160Python 2 and 3 by the same sourcecode (without using 2to3). It was required to
30 unmodified lines
191templates passing information to the parent template. To avoid this192issue rename the macro or variable in the parent template to have an193uncommon prefix.194195.. _Jinja 1: http://jinja.pocoo.org/1/195.. _Jinja 1: https://pypi.org/project/Jinja/
modified:docs/index.rst+24 added-7 removed
1Welcome to Jinja22=================1.. rst-class:: hide-header23Jinja4=====56.. image:: _static/jinja-logo.png7 :align: center8 :target: https://palletsprojects.com/p/jinja/94Jinja2 is a modern and designer-friendly templating language for Python,10Jinja is a modern and designer-friendly templating language for Python,11modelled after Django's templates. It is fast, widely used and secure12with the optional sandboxed template execution environment:1314.. sourcecode:: html+jinja
4 unmodified lines
19 <li><a href="{{ user.url }}">{{ user.username }}</a></li>20 {% endfor %}21 </ul>2217**Features:**23Features:2425- sandboxed execution26- powerful automatic HTML escaping system for XSS prevention27- template inheritance
2 unmodified lines
30- easy to debug. Line numbers of exceptions directly point to31 the correct line in the template.32- configurable syntax3328.. include:: contents.rst.inc34.. toctree::35 :maxdepth: 236 :caption: Contents:3730If you can't find the information you're looking for, have a look at the31index or try to find it using the search function:38 intro39 api40 sandbox41 nativetypes42 templates43 extensions44 integration45 switching46 tricks47 faq48 changelog4950* :ref:`genindex`51* :ref:`search`
modified:docs/integration.rst+2 added-2 removed
74 unmodified lines
75snippet and add it into your `config/environment.py`::7677 config['pylons.strict_c'] = True7879.. _Pylons: http://www.pylonshq.com/79.. _Pylons: https://pylonshq.com/8081TextMate82--------83
17 unmodified lines
101<https://github.com/mitsuhiko/vim-jinja>`_ repository for installing in the102``bundle/`` directory.103104.. _Babel: http://babel.pocoo.org/105.. _Vim: http://www.vim.org/105.. _Vim: https://www.vim.org/106.. _Pathogen: https://github.com/tpope/vim-pathogen
modified:docs/intro.rst+3 added-3 removed
40 unmodified lines
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: http://peak.telecommunity.com/DevCenter/setuptools45.. _setuptools: https://pypi.org/project/setuptools/46.. _pip: https://pypi.org/project/pip/47.. _git: https://git-scm.org/47.. _git: https://git-scm.com/484950MarkupSafe Dependency51~~~~~~~~~~~~~~~~~~~~~5253As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you install54Jinja2 via ``pip`` it will be installed automatically for you.5556.. _MarkupSafe: https://pypi.org/project/MarkupSafe/56.. _MarkupSafe: https://markupsafe.palletsprojects.com/5758Basic API Usage59---------------60
22 unmodified lines
deleted:docs/jinjaext.py-206 removed
1# -*- coding: utf-8 -*-2"""3 Jinja Documentation Extensions4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Support for automatically documenting filters and tests.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import os12import re13import inspect1415import logging1617import jinja218from itertools import islice19from types import BuiltinFunctionType20from docutils import nodes21from docutils.statemachine import ViewList22from sphinx.ext.autodoc import prepare_docstring23from sphinx.application import TemplateBridge24from pygments.style import Style25from pygments.token import Keyword, Name, Comment, String, Error, \26 Number, Operator, Generic27from jinja2 import Environment, FileSystemLoader28from jinja2._compat import abc293031def parse_rst(state, content_offset, doc):32 node = nodes.section()33 # hack around title style bookkeeping34 surrounding_title_styles = state.memo.title_styles35 surrounding_section_level = state.memo.section_level36 state.memo.title_styles = []37 state.memo.section_level = 038 state.nested_parse(doc, content_offset, node, match_titles=1)39 state.memo.title_styles = surrounding_title_styles40 state.memo.section_level = surrounding_section_level41 return node.children424344class JinjaStyle(Style):45 title = 'Jinja Style'46 default_style = ""47 styles = {48 Comment: 'italic #aaaaaa',49 Comment.Preproc: 'noitalic #B11414',50 Comment.Special: 'italic #505050',5152 Keyword: 'bold #B80000',53 Keyword.Type: '#808080',5455 Operator.Word: 'bold #B80000',5657 Name.Builtin: '#333333',58 Name.Function: '#333333',59 Name.Class: 'bold #333333',60 Name.Namespace: 'bold #333333',61 Name.Entity: 'bold #363636',62 Name.Attribute: '#686868',63 Name.Tag: 'bold #686868',64 Name.Decorator: '#686868',6566 String: '#AA891C',67 Number: '#444444',6869 Generic.Heading: 'bold #000080',70 Generic.Subheading: 'bold #800080',71 Generic.Deleted: '#aa0000',72 Generic.Inserted: '#00aa00',73 Generic.Error: '#aa0000',74 Generic.Emph: 'italic',75 Generic.Strong: 'bold',76 Generic.Prompt: '#555555',77 Generic.Output: '#888888',78 Generic.Traceback: '#aa0000',7980 Error: '#F00 bg:#FAA'81 }828384_sig_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\(.*?\))')858687def format_function(name, aliases, func):88 lines = inspect.getdoc(func).splitlines()89 signature = '()'90 if isinstance(func, BuiltinFunctionType):91 match = _sig_re.match(lines[0])92 if match is not None:93 del lines[:1 + bool(lines and not lines[0])]94 signature = match.group(1)95 else:96 try:97 argspec = inspect.getargspec(func)98 if getattr(func, 'environmentfilter', False) or \99 getattr(func, 'contextfilter', False) or \100 getattr(func, 'evalcontextfilter', False):101 del argspec[0][0]102 signature = inspect.formatargspec(*argspec)103 except:104 pass105 result = ['.. function:: %s%s' % (name, signature), '']106 result.extend(' ' + line for line in lines)107 if aliases:108 result.extend(('', ' :aliases: %s' % ', '.join(109 '``%s``' % x for x in sorted(aliases))))110 return result111112113def dump_functions(mapping):114 def directive(115 dirname, arguments, options, content, lineno, content_offset,116 block_text, state, state_machine117 ):118 reverse_mapping = {}119120 for name, func in mapping.items():121 reverse_mapping.setdefault(func, []).append(name)122123 filters = []124 compare_ops = set(('lt', 'le', 'eq', 'ne', 'ge', 'gt'))125126 for func, names in reverse_mapping.items():127 aliases = sorted(names, key=len)128 aliases = sorted(aliases, key=lambda x: x in compare_ops)129 name = aliases.pop()130 filters.append((name, aliases, func))131132 filters.sort()133 result = ViewList()134135 for name, aliases, func in filters:136 for item in format_function(name, aliases, func):137 result.append(item, '<jinjaext>')138139 node = nodes.paragraph()140 state.nested_parse(result, content_offset, node)141 return node.children142143 return directive144145146from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS147jinja_filters = dump_functions(DEFAULT_FILTERS)148jinja_tests = dump_functions(DEFAULT_TESTS)149150151def jinja_nodes(dirname, arguments, options, content, lineno,152 content_offset, block_text, state, state_machine):153 from jinja2.nodes import Node154 doc = ViewList()155 def walk(node, indent):156 p = ' ' * indent157 sig = ', '.join(node.fields)158 doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '')159 if node.abstract:160 members = []161 for key, name in node.__dict__.items():162 if not key.startswith('_') and \163 not hasattr(node.__base__, key) and isinstance(name, abc.Callable):164 members.append(key)165 if members:166 members.sort()167 doc.append('%s :members: %s' % (p, ', '.join(members)), '')168 if node.__base__ != object:169 doc.append('', '')170 doc.append('%s :Node type: :class:`%s`' %171 (p, node.__base__.__name__), '')172 doc.append('', '')173 children = node.__subclasses__()174 children.sort(key=lambda x: x.__name__.lower())175 for child in children:176 walk(child, indent)177 walk(Node, 0)178 return parse_rst(state, content_offset, doc)179180181def inject_toc(app, doctree, docname):182 titleiter = iter(doctree.traverse(nodes.title))183 try:184 # skip first title, we are not interested in that one185 next(titleiter)186 title = next(titleiter)187 # and check if there is at least another title188 next(titleiter)189 except StopIteration:190 return191 tocnode = nodes.section('')192 tocnode['classes'].append('toc')193 toctitle = nodes.section('')194 toctitle['classes'].append('toctitle')195 toctitle.append(nodes.title(text='Table Of Contents'))196 tocnode.append(toctitle)197 tocnode += doctree.document.settings.env.get_toc_for(docname)[0][1]198 title.parent.insert(title.parent.children.index(title), tocnode)199200201def setup(app):202 app.add_directive('jinjafilters', jinja_filters, 0, (0, 0, 0))203 app.add_directive('jinjatests', jinja_tests, 0, (0, 0, 0))204 app.add_directive('jinjanodes', jinja_nodes, 0, (0, 0, 0))205 # uncomment for inline toc. links are broken unfortunately206 ##app.connect('doctree-resolved', inject_toc)
deleted:docs/jinjastyle.sty-119 removed
1\definecolor{TitleColor}{rgb}{0,0,0}2\definecolor{InnerLinkColor}{rgb}{0,0,0}3\definecolor{OuterLinkColor}{rgb}{0.8,0,0}45\renewcommand{\maketitle}{%6 \begin{titlepage}%7 \let\footnotesize\small8 \let\footnoterule\relax9 \ifsphinxpdfoutput10 \begingroup11 % This \def is required to deal with multi-line authors; it12 % changes \\ to ', ' (comma-space), making it pass muster for13 % generating document info in the PDF file.14 \def\\{, }15 \pdfinfo{16 /Author (\@author)17 /Title (\@title)18 }19 \endgroup20 \fi21 \begin{flushright}%22 %\sphinxlogo%23 {\center24 \vspace*{3cm}25 \includegraphics{logo.pdf}26 \vspace{3cm}27 \par28 {\rm\Huge \@title \par}%29 {\em\LARGE \py@release\releaseinfo \par}30 {\large31 \@date \par32 \py@authoraddress \par33 }}%34 \end{flushright}%\par35 \@thanks36 \end{titlepage}%37 \cleardoublepage%38 \setcounter{footnote}{0}%39 \let\thanks\relax\let\maketitle\relax40 %\gdef\@thanks{}\gdef\@author{}\gdef\@title{}41}4243\fancypagestyle{normal}{44 \fancyhf{}45 \fancyfoot[LE,RO]{{\thepage}}46 \fancyfoot[LO]{{\nouppercase{\rightmark}}}47 \fancyfoot[RE]{{\nouppercase{\leftmark}}}48 \fancyhead[LE,RO]{{ \@title, \py@release}}49 \renewcommand{\headrulewidth}{0.4pt}50 \renewcommand{\footrulewidth}{0.4pt}51}5253\fancypagestyle{plain}{54 \fancyhf{}55 \fancyfoot[LE,RO]{{\thepage}}56 \renewcommand{\headrulewidth}{0pt}57 \renewcommand{\footrulewidth}{0.4pt}58}5960\titleformat{\section}{\Large}%61 {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor}62\titleformat{\subsection}{\large}%63 {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor}64\titleformat{\subsubsection}{}%65 {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor}66\titleformat{\paragraph}{\large}%67 {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor}6869\ChNameVar{\raggedleft\normalsize}70\ChNumVar{\raggedleft \bfseries\Large}71\ChTitleVar{\raggedleft \rm\Huge}7273\renewcommand\thepart{\@Roman\c@part}74\renewcommand\part{%75 \pagestyle{plain}76 \if@noskipsec \leavevmode \fi77 \cleardoublepage78 \vspace*{6cm}%79 \@afterindentfalse80 \secdef\@part\@spart}8182\def\@part[#1]#2{%83 \ifnum \c@secnumdepth >\m@ne84 \refstepcounter{part}%85 \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}%86 \else87 \addcontentsline{toc}{part}{#1}%88 \fi89 {\parindent \z@ %\center90 \interlinepenalty \@M91 \normalfont92 \ifnum \c@secnumdepth >\m@ne93 \rm\Large \partname~\thepart94 \par\nobreak95 \fi96 \MakeUppercase{\rm\Huge #2}%97 \markboth{}{}\par}%98 \nobreak99 \vskip 8ex100 \@afterheading}101\def\@spart#1{%102 {\parindent \z@ %\center103 \interlinepenalty \@M104 \normalfont105 \huge \bfseries #1\par}%106 \nobreak107 \vskip 3ex108 \@afterheading}109110% use inconsolata font111\usepackage{inconsolata}112113% fix single quotes, for inconsolata. (does not work)114%%\usepackage{textcomp}115%%\begingroup116%% \catcode`'=\active117%% \g@addto@macro\@noligs{\let'\textsinglequote}118%% \endgroup119%%\endinput
deleted:docs/latexindex.rst-6 removed
1:orphan:23Jinja2 Documentation4====================56.. include:: contents.rst.inc
deleted:docs/logo.pdfbinary

A binary file, deleted.

added:docs/make.bat+35 added
1@ECHO OFF23pushd %~dp045REM Command file for Sphinx documentation67if "%SPHINXBUILD%" == "" (8 set SPHINXBUILD=sphinx-build9)10set SOURCEDIR=.11set BUILDDIR=_build1213if "%1" == "" goto help1415%SPHINXBUILD% >NUL 2>NUL16if errorlevel 9009 (17 echo.18 echo.The 'sphinx-build' command was not found. Make sure you have Sphinx19 echo.installed, then set the SPHINXBUILD environment variable to point20 echo.to the full path of the 'sphinx-build' executable. Alternatively you21 echo.may add the Sphinx directory to PATH.22 echo.23 echo.If you don't have Sphinx installed, grab it from24 echo.http://sphinx-doc.org/25 exit /b 126)2728%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%29goto end3031:help32%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%3334:end35popd
modified:docs/Makefile+9 added-108 removed
1# Makefile for Sphinx documentation1# Minimal makefile for Sphinx documentation2#34# You can set these variables from the command line.5SPHINXOPTS =6SPHINXBUILD = sphinx-build7PAPER =7SOURCEDIR = .8BUILDDIR = _build910# Internal variables.11PAPEROPT_a4 = -D latex_paper_size=a412PAPEROPT_letter = -D latex_paper_size=letter13ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .1415.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp epub latex changes linkcheck doctest1610# Put it first so that "make" without argument is like "make help".11help:18 @echo "Please use \`make <target>' where <target> is one of"19 @echo " html to make standalone HTML files"20 @echo " dirhtml to make HTML files named index.html in directories"21 @echo " singlehtml to make a single large HTML file"22 @echo " pickle to make pickle files"23 @echo " json to make JSON files"24 @echo " htmlhelp to make HTML files and a HTML help project"25 @echo " qthelp to make HTML files and a qthelp project"26 @echo " devhelp to make HTML files and a Devhelp project"27 @echo " epub to make an epub"28 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"29 @echo " latexpdf to make LaTeX files and run them through pdflatex"30 @echo " changes to make an overview of all changed/added/deprecated items"31 @echo " linkcheck to check all external links for integrity"32 @echo " doctest to run all doctests embedded in the documentation (if enabled)"12 @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)1334clean:35 -rm -rf $(BUILDDIR)/*14.PHONY: help Makefile1537html:38 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html39 @echo40 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."4142dirhtml:43 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml44 @echo45 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."4647singlehtml:48 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml49 @echo50 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."5152pickle:53 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle54 @echo55 @echo "Build finished; now you can process the pickle files."5657json:58 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json59 @echo60 @echo "Build finished; now you can process the JSON files."6162htmlhelp:63 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp64 @echo65 @echo "Build finished; now you can run HTML Help Workshop with the" \66 ".hhp project file in $(BUILDDIR)/htmlhelp."6768qthelp:69 $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp70 @echo71 @echo "Build finished; now you can run "qcollectiongenerator" with the" \72 ".qhcp project file in $(BUILDDIR)/qthelp, like this:"73 @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask.qhcp"74 @echo "To view the help file:"75 @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask.qhc"7677devhelp:78 $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) _build/devhelp79 @echo80 @echo "Build finished."81 @echo "To view the help file:"82 @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask"83 @echo "# ln -s _build/devhelp $$HOME/.local/share/devhelp/Flask"84 @echo "# devhelp"8586epub:87 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub88 @echo89 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."9091latex:92 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex93 @echo94 @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."95 @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \96 "run these through (pdf)latex."9798latexpdf: latex99 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex100 @echo "Running LaTeX files through pdflatex..."101 make -C _build/latex all-pdf102 @echo "pdflatex finished; the PDF files are in _build/latex."103104changes:105 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes106 @echo107 @echo "The overview file is in $(BUILDDIR)/changes."108109linkcheck:110 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck111 @echo112 @echo "Link check complete; look for any errors in the above output " \113 "or in $(BUILDDIR)/linkcheck/output.txt."114115doctest:116 $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest117 @echo "Testing of doctests in the sources finished, look at the " \118 "results in $(BUILDDIR)/doctest/output.txt."16# Catch-all target: route all unknown targets to Sphinx using the new17# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).18%: Makefile19 @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
added:docs/requirements.txt+4 added
1Sphinx~=2.1.22Pallets-Sphinx-Themes~=1.2.03sphinxcontrib-log-cabinet~=1.0.14sphinx-issues~=1.2.0
modified:docs/templates.rst+98 added-38 removed
393 unmodified lines
394this template "extends" another template. When the template system evaluates395this template, it first locates the parent. The extends tag should be the396first tag in the template. Everything before it is printed out normally and397may cause confusion. For details about this behavior and how to take398advantage of it, see :ref:`null-master-fallback`.398advantage of it, see :ref:`null-master-fallback`. Also a block will always be399filled in regardless of whether the surrounding condition is evaluated to be true400or false.401402The filename of the template depends on the template loader. For example, the403:class:`FileSystemLoader` allows you to access other templates by giving the404filename. You can access templates in subdirectories with a slash::
21 unmodified lines
426427Super Blocks428~~~~~~~~~~~~429428It's possible to render the contents of the parent block by calling `super`.430It's possible to render the contents of the parent block by calling ``super()``.431This gives back the results of the parent block::432433 {% block sidebar %}434 <h3>Table Of Contents</h3>
1 unmodified line
436 {{ super() }}437 {% endblock %}438439440Nesting extends441~~~~~~~~~~~~~~~442443In the case of multiple levels of ``{% extends %}``,444``super`` references may be chained (as in ``super.super()``)445to skip levels in the inheritance tree.446447For example::448449 # parent.tmpl450 body: {% block body %}Hi from parent.{% endblock %}451452 # child.tmpl453 {% extends "parent.tmpl" %}454 {% block body %}Hi from child. {{ super() }}{% endblock %}455456 # grandchild1.tmpl457 {% extends "child.tmpl" %}458 {% block body %}Hi from grandchild1.{% endblock %}459460 # grandchild2.tmpl461 {% extends "child.tmpl" %}462 {% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}463464465Rendering ``child.tmpl`` will give466``body: Hi from child. Hi from parent.``467468Rendering ``grandchild1.tmpl`` will give469``body: Hi from grandchild1.``470471Rendering ``grandchild2.tmpl`` will give472``body: Hi from grandchild2. Hi from parent.``473474475Named Block End-Tags476~~~~~~~~~~~~~~~~~~~~477478Jinja2 allows you to put the name of the block after the end tag for better
134 unmodified lines
613As variables in templates retain their object properties, it is possible to614iterate over containers like `dict`::615616 <dl>580 {% for key, value in my_dict.iteritems() %}617 {% for key, value in my_dict.items() %}618 <dt>{{ key|e }}</dt>619 <dd>{{ value|e }}</dd>620 {% endfor %}621 </dl>
554 unmodified lines
1176 useful whenever you need a string in the template (e.g. as1177 arguments to function calls and filters, or just to extend or include a1178 template).1179114342 / 42.23:1144 Integers and floating point numbers are created by just writing the1145 number down. If a dot is present, the number is a float, otherwise an1146 integer. Keep in mind that, in Python, ``42`` and ``42.0``1147 are different (``int`` and ``float``, respectively).118042 / 123_456:1181 Integers are whole numbers without a decimal part. The '_' character1182 can be used to separate groups for legibility.1183118442.23 / 42.1e2 / 123_456.789:1185 Floating point numbers can be written using a '.' as a decimal mark.1186 They can also be written in scientific notation with an upper or1187 lower case 'e' to indicate the exponent part. The '_' character can1188 be used to separate groups for legibility, but cannot be used in the1189 exponent part.11901191['list', 'of', 'objects']:1192 Everything between two brackets is a list. Lists are useful for storing1193 sequential data to be iterated over. For example, you can easily1194 create a list of links using lists and tuples for (and with) a for loop::
47 unmodified lines
12421243/1244 Divide two numbers. The return value will be a floating point number.1245 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.1204 (Just like ``from __future__ import division``.)12461247//1248 Divide two numbers and return the truncated integer result.1249 ``{{ 20 // 7 }}`` is ``2``.
106 unmodified lines
13561357The `else` part is optional. If not provided, the else block implicitly1358evaluates into an undefined object:13591360.. sourcecode:: jinja13611362 {{ "[{}]".format(page.title) if page.title }}136313641365.. _python-methods:13661367Python Methods1368~~~~~~~~~~~~~~13691370You can also use any of the methods of defined on a variable's type.1371The value returned from the method invocation is used as the value of the expression.1372Here is an example that uses methods defined on strings (where ``page.title`` is a string):13731374.. code-block:: text13751321 {{ ('[%s]' % page.title) if page.title }}1376 {{ page.title.capitalize() }}13771378This also works for methods on user-defined types.1379For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1380you can do the following:13811382.. code-block:: text13831384 {{ f.bar() }}138513861387.. _builtin-filters:13881389List of Builtin Filters1390-----------------------13911329=================== =================== ================== ====================== ====================1330Built-in Filters Index1331==========================================================================================================1332:func:`abs` :func:`attr` :func:`batch` :func:`capitalize` :func:`center`1333:func:`default` :func:`dictsort` :func:`escape` :func:`filesizeformat` :func:`first`1334:func:`float` :func:`forceescape` :func:`format` :func:`groupby` :func:`indent`1335:func:`int` :func:`join` :func:`last` :func:`length` :func:`list`1336:func:`lower` :func:`map` :func:`max` :func:`min` :func:`pprint`1337:func:`random` :func:`reject` :func:`rejectattr` :func:`replace` :func:`reverse`1338:func:`round` :func:`safe` :func:`select` :func:`selectattr` :func:`slice`1339:func:`sort` :func:`string` :func:`striptags` :func:`sum` :func:`title`1340:func:`tojson` :func:`trim` :func:`truncate` :func:`unique` :func:`upper`1341:func:`urlencode` :func:`urlize` :func:`wordcount` :func:`wordwrap` :func:`xmlattr`1342=================== =================== ================== ====================== ====================1392.. jinja:filters:: jinja2.defaults.DEFAULT_FILTERS1393139413451346.. jinjafilters::134713481395.. _builtin-tests:13961397List of Builtin Tests1398---------------------13991354=================== ================== =================== ================ ================1355Built-in Test Index1356================================================================================================1357:func:`callable` :func:`defined` :func:`divisibleby` :func:`eq` :func:`escaped`1358:func:`even` :func:`ge` :func:`gt` :func:`in` :func:`iterable`1359:func:`le` :func:`lower` :func:`lt` :func:`mapping` :func:`ne`1360:func:`none` :func:`number` :func:`odd` :func:`sameas` :func:`sequence`1361:func:`string` :func:`undefined` .. .. ..1362=================== ================== =================== ================ ================1400.. jinja:tests:: jinja2.defaults.DEFAULT_TESTS14011364.. jinjatests::14021403.. _builtin-globals:14041405List of Global Functions
251 unmodified lines
1657Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 01658(See: :ref:`for-loop`).165916601661Debug Statement1662~~~~~~~~~~~~~~~16631664If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be1665available to dump the current context as well as the available filters1666and tests. This is useful to see what's available to use in the template1667without setting up a debugger.16681669.. code-block:: html+jinja16701671 <pre>{% debug %}</pre>16721673.. code-block:: text16741675 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,1676 ...,1677 'namespace': <class 'jinja2.utils.Namespace'>},1678 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',1679 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],1680 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',1681 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}168216831684With Statement1685~~~~~~~~~~~~~~16861687.. versionadded:: 2.3
74 unmodified lines
modified:ext/Vim/jinja.vim+3 added
80 unmodified lines
81syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment8283" Jinja comments84syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment85" help support folding for some setups86setlocal commentstring={#%s#}87setlocal comments=s:{#,e:#}8889" Block start keywords. A bit tricker. We only highlight at the start of a90" tag block and only if the name is not followed by a comma or equals sign91" which usually means that we have to deal with an assignment.
47 unmodified lines
modified:ext/inlinegettext.py+1 added-1 removed
30 unmodified lines
31 def filter_stream(self, stream):32 paren_stack = 03334 for token in stream:35 if token.type is not 'data':35 if token.type != 'data':36 yield token37 continue3839 pos = 0
39 unmodified lines
modified:jinja2/__init__.py+3 added-3 removed
25 unmodified lines
26 :copyright: (c) 2017 by the Jinja Team.27 :license: BSD, see LICENSE for more details.28"""29__docformat__ = 'restructuredtext en'30__version__ = '2.11.dev'30__version__ = "2.11.0.dev0"3132# high level interface33from jinja2.environment import Environment, Template34
6 unmodified lines
41from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache4344# undefined types45from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46 make_logging_undefined45from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46 StrictUndefined, make_logging_undefined4748# exceptions49from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \
22 unmodified lines
modified:jinja2/bccache.py+5 added-6 removed
1 unmodified line
2"""3 jinja2.bccache4 ~~~~~~~~~~~~~~56 This module implements the bytecode cache system Jinja is optionally7 using. This is useful if you have very complex template situations and8 the compiliation of all those templates slow down your application too6 This module implements the bytecode cache system that Jinja optionally uses.7 This is useful if you have very complex template situations and8 the compilation of all those templates slows down your application too9 much.1011 Situations where this is useful are often forking web applications that12 are initialized on the first request.
282 unmodified lines
295 the minimal interface required.296297 Libraries compatible with this class:298299 - `werkzeug <http://werkzeug.pocoo.org/>`_.contrib.cache300 - `python-memcached <https://www.tummy.com/Community/software/python-memcached/>`_301 - `cmemcache <http://gijsbert.org/cmemcache/>`_299 - `cachelib <https://github.com/pallets/cachelib>`_300 - `python-memcached <https://pypi.org/project/python-memcached/>`_301302 (Unfortunately the django cache interface is not compatible because it303 does not support storing binary data, only unicode. You can however pass304 the underlying cache client to the bytecode cache which is available
57 unmodified lines
modified:jinja2/debug.py+11 added-5 removed
363 unmodified lines
364# try to get a tb_set_next implementation if we don't have transparent365# proxies.366tb_set_next = None367if tproxy is None:368 # traceback.tb_next can be modified since CPython 3.7369 if sys.version_info >= (3, 7):370 def tb_set_next(tb, next):371 tb.tb_next = next372 else:373 # On Python 3.6 and older, use ctypes368 try:369 tb_set_next = _init_ugly_crap()370 except:371 pass372 del _init_ugly_crap374 try:375 tb_set_next = _init_ugly_crap()376 except Exception:377 pass378del _init_ugly_crap
modified:jinja2/exceptions.py+1 added-1 removed
48 unmodified lines
49 # bogusly warns us about message being deprecated50 message = None5152 def __init__(self, name, message=None):53 IOError.__init__(self)53 IOError.__init__(self, name)54 if message is None:55 message = name56 self.message = message57 self.name = name
89 unmodified lines
modified:jinja2/ext.py+54 added-3 removed
1 unmodified line
2"""3 jinja2.ext4 ~~~~~~~~~~56 Jinja extensions allow to add custom tags similar to the way django custom7 tags work. By default two example extensions exist: an i18n and a cache8 extension.6 Jinja extensions allow adding custom tags and behavior. The7 following extensions are included:89 - An 18n support ``{% trans %}`` tag.10 - A ``{% do %}`` tag.11 - Loop control ``{% break %}`` and ``{% continue %}`` tags.12 - A ``{% debug %}`` tag.1314 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD.16"""17import pprint18import re19from sys import version_info2021from jinja2 import nodes22from jinja2.defaults import BLOCK_START_STRING, \23 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \24 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \25 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \26 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS27from jinja2.environment import Environment28from jinja2.nodes import ContextReference29from jinja2.runtime import concat30from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError31from jinja2.utils import contextfunction, import_string, Markup32from jinja2._compat import with_metaclass, string_types, iteritems33from markupsafe import escape343536# the only real useful gettext functions for a Jinja template. Note37# that ugettext must be assigned to gettext as Jinja doesn't support
403 unmodified lines
441class AutoEscapeExtension(Extension):442 pass443444445class DebugExtension(Extension):446 """A ``{% debug %}`` tag that dumps the available variables,447 filters, and tests.448449 .. code-block:: html+jinja450451 <pre>{% debug %}</pre>452453 .. code-block:: text454455 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,456 ...,457 'namespace': <class 'jinja2.utils.Namespace'>},458 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',459 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],460 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',461 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}462463 .. versionadded:: 2.11.0464 """465 tags = {'debug'}466467 def parse(self, parser):468 lineno = parser.stream.expect("name:debug").lineno469 context = ContextReference()470 result = self.call_method("_render", [context], lineno=lineno)471 return nodes.Output([result], lineno=lineno)472473 def _render(self, context):474 result = {475 "context": context.get_all(),476 "filters": sorted(self.environment.filters.keys()),477 "tests": sorted(self.environment.tests.keys()),478 }479480 # Set the depth since the intent is to show the top few names.481 if version_info[:2] >= (3, 4):482 return pprint.pformat(result, depth=3, compact=True)483 else:484 return pprint.pformat(result, depth=3)485486487def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,488 babel_style=True):489 """Extract localizable strings from the given template node. Per490 default this function returns matches in babel style that means non string
183 unmodified lines
674do = ExprStmtExtension675loopcontrols = LoopControlExtension676with_ = WithExtension677autoescape = AutoEscapeExtension678debug = DebugExtension
modified:jinja2/filters.py+123 added-56 removed
57 unmodified lines
58 to lowercase and returns other types as-is."""59 return value.lower() if isinstance(value, string_types) else value606162def make_attrgetter(environment, attribute, postprocess=None):62def make_attrgetter(environment, attribute, postprocess=None, default=None):63 """Returns a callable that looks up the given attribute from a64 passed object with the rules of the environment. Dots are allowed65 to access attributes of attributes. Integer parts in paths are66 looked up as integers.67 """68 if attribute is None:69 attribute = []70 elif isinstance(attribute, string_types):71 attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]72 else:73 attribute = [attribute]68 attribute = _prepare_attribute_parts(attribute)6970 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)7374 if default and isinstance(item, Undefined):75 item = default7677 if postprocess is not None:78 item = postprocess(item)7980 return item8182 return attrgetter838485def make_multi_attrgetter(environment, attribute, postprocess=None):86 """Returns a callable that looks up the given comma separated87 attributes from a passed object with the rules of the environment.88 Dots are allowed to access attributes of each attribute. Integer89 parts in paths are looked up as integers.9091 The value returned by the returned callable is a list of extracted92 attribute values.9394 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.95 """96 attribute_parts = attribute.split(',') if isinstance(attribute, string_types) else [attribute]97 attribute = [_prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts]9899 def attrgetter(item):100 items = [None] * len(attribute)101 for i, attribute_part in enumerate(attribute):102 item_i = item103 for part in attribute_part:104 item_i = environment.getitem(item_i, part)105106 if postprocess is not None:107 item_i = postprocess(item_i)108109 items[i] = item_i110 return items111112 return attrgetter113114115def _prepare_attribute_parts(attr):116 if attr is None:117 return []118 elif isinstance(attr, string_types):119 return [int(x) if x.isdigit() else x for x in attr.split('.')]120 else:121 return [attr]122123124def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, '__html__'):127 value = value.__html__()
151 unmodified lines
279 return sorted(value.items(), key=sort_func, reverse=reverse)280281282@environmentfilter246def do_sort(247 environment, value, reverse=False, case_sensitive=False, attribute=None248):249 """Sort an iterable. Per default it sorts ascending, if you pass it250 true as first argument it will reverse the sorting.283def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):284 """Sort an iterable using Python's :func:`sorted`.285252 If the iterable is made of strings the third parameter can be used to253 control the case sensitiveness of the comparison which is disabled by254 default.286 .. sourcecode:: jinja287288 {% for city in cities|sort %}289 ...290 {% endfor %}291292 :param reverse: Sort descending instead of ascending.293 :param case_sensitive: When sorting strings, sort upper and lower294 case separately.295 :param attribute: When sorting objects or dicts, an attribute or296 key to sort by. Can use dot notation like ``"address.city"``.297 Can be a list of attributes like ``"age,name"``.298299 The sort is stable, it does not change the relative order of300 elements that compare equal. This makes it is possible to chain301 sorts on different attributes and ordering.302303 .. sourcecode:: jinja304258 {% for item in iterable|sort %}305 {% for user in users|sort(attribute="name")|sort(reverse=true, attribute="age") %}306 ...307 {% endfor %}308262 It is also possible to sort by an attribute (for example to sort263 by the date of an object) by specifying the `attribute` parameter:309 As a shortcut to chaining when the direction is the same for all310 attributes, pass a comma separate list of attributes.311312 .. sourcecode:: jinja313267 {% for item in iterable|sort(attribute='date') %}314 {% for user users|sort(attribute="age,name") %}315 ...316 {% endfor %}317318 .. versionchanged:: 2.11.0319 The ``attribute`` parameter can be a comma separated list of320 attributes, e.g. ``"age,name"``.321322 .. versionchanged:: 2.6272 The `attribute` parameter was added.323 The ``attribute`` parameter was added.324 """274 key_func = make_attrgetter(325 key_func = make_multi_attrgetter(326 environment, attribute,327 postprocess=ignore_case if not case_sensitive else None328 )329 return sorted(value, key=key_func, reverse=reverse)330331332@environmentfilter333def do_unique(environment, value, case_sensitive=False, attribute=None):283 """Returns a list of unique items from the the given iterable.334 """Returns a list of unique items from the given iterable.335336 .. sourcecode:: jinja337287 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}338 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}339 -> ['foo', 'bar', 'foobar']340341 The unique items are yielded in the same order as their first occurrence in342 the iterable passed to the filter.
23 unmodified lines
366 except StopIteration:367 return environment.undefined('No aggregated item, sequence was empty.')368369 key_func = make_attrgetter(319 environment, attribute,320 ignore_case if not case_sensitive else None370 environment,371 attribute,372 postprocess=ignore_case if not case_sensitive else None373 )374 return func(chain([first], it), key=key_func)375376
42 unmodified lines
419420 .. sourcecode:: jinja421422 {{ ''|default('the string was empty', true) }}423424 .. versionchanged:: 2.11425 It's now possible to configure the :class:`~jinja2.Environment` with426 :class:`~jinja2.ChainableUndefined` to make the `default` filter work427 on nested elements and attributes that may contain undefined values428 in the chain without getting an :exc:`~jinja2.UndefinedError`.429 """430 if isinstance(value, Undefined) or (boolean and not value):431 return default_value432 return value
323 unmodified lines
756 'arguments at the same time')757 return soft_unicode(value) % (kwargs or args)758759702def do_trim(value):703 """Strip leading and trailing whitespace."""704 return soft_unicode(value).strip()760def do_trim(value, chars=None):761 """Strip leading and trailing characters, by default whitespace."""762 return soft_unicode(value).strip(chars)763764765def do_striptags(value):766 """Strip SGML/XML tags and replace adjacent whitespace by one space.
9 unmodified lines
776 three ul tags that represent columns:777778 .. sourcecode:: html+jinja779722 <div class="columwrapper">780 <div class="columnwrapper">781 {%- for column in items|slice(3) %}782 <ul class="column-{{ loop.index }}">783 {%- for item in column %}784 <li>{{ item }}</li>
94 unmodified lines
879_GroupTuple = namedtuple('_GroupTuple', ['grouper', 'list'])880_GroupTuple.__repr__ = tuple.__repr__881_GroupTuple.__str__ = tuple.__str__882883884@environmentfilter885def do_groupby(environment, value, attribute):827 """Group a sequence of objects by a common attribute.886 """Group a sequence of objects by an attribute using Python's887 :func:`itertools.groupby`. The attribute can use dot notation for888 nested access, like ``"address.city"``. Unlike Python's ``groupby``,889 the values are sorted first so only one group is returned for each890 unique value.891829 If you for example have a list of dicts or objects that represent persons830 with `gender`, `first_name` and `last_name` attributes and you want to831 group all users by genders you can do something like the following832 snippet:892 For example, a list of ``User`` objects with a ``city`` attribute893 can be rendered in groups. In this example, ``grouper`` refers to894 the ``city`` value of the group.895896 .. sourcecode:: html+jinja897836 <ul>837 {% for group in persons|groupby('gender') %}838 <li>{{ group.grouper }}<ul>839 {% for person in group.list %}840 <li>{{ person.first_name }} {{ person.last_name }}</li>841 {% endfor %}</ul></li>842 {% endfor %}843 </ul>898 <ul>{% for city, items in users|groupby("city") %}899 <li>{{ city }}900 <ul>{% for user in items %}901 <li>{{ user.name }}902 {% endfor %}</ul>903 </li>904 {% endfor %}</ul>905845 Additionally it's possible to use tuple unpacking for the grouper and846 list:906 ``groupby`` yields namedtuples of ``(grouper, list)``, which907 can be used instead of the tuple unpacking above. ``grouper`` is the908 value of the attribute, and ``list`` is the items with that value.909910 .. sourcecode:: html+jinja911850 <ul>851 {% for grouper, list in persons|groupby('gender') %}852 ...853 {% endfor %}854 </ul>912 <ul>{% for group in users|groupby("city") %}913 <li>{{ group.grouper }}: {{ group.list|join(", ") }}914 {% endfor %}</ul>915856 As you can see the item we're grouping by is stored in the `grouper`857 attribute and the `list` contains all the objects that have this grouper858 in common.859916 .. versionchanged:: 2.6861 It's now possible to use dotted notation to group by the child862 attribute of another attribute.917 The attribute supports dot notation for nested access.918 """919 expr = make_attrgetter(environment, attribute)920 return [_GroupTuple(key, list(values)) for key, values921 in groupby(sorted(value, key=expr), expr)]
93 unmodified lines
1015 .. sourcecode:: jinja10161017 Users on this page: {{ users|map(attribute='username')|join(', ') }}10181019 You can specify a ``default`` value to use if an object in the list1020 does not have the given attribute.10211022 .. sourcecode:: jinja10231024 {{ users|map(attribute="username", default="Anonymous")|join(", ") }}10251026 Alternatively you can let it invoke a filter by passing the name of the1027 filter and the arguments afterwards. A good example would be applying a1028 text conversion filter on a sequence:10291030 .. sourcecode:: jinja10311032 Users on this page: {{ titles|map('lower')|join(', ') }}10331034 .. versionchanged:: 2.11.01035 Added the ``default`` parameter.10361037 .. versionadded:: 2.71038 """1039 seq, func = prepare_map(args, kwargs)1040 if seq:
118 unmodified lines
11591160def prepare_map(args, kwargs):1161 context = args[0]1162 seq = args[1]1163 default = None11641165 if len(args) == 2 and 'attribute' in kwargs:1166 attribute = kwargs.pop('attribute')1167 default = kwargs.pop('default', None)1168 if kwargs:1169 raise FilterArgumentError('Unexpected keyword argument %r' %1170 next(iter(kwargs)))1104 func = make_attrgetter(context.environment, attribute)1171 func = make_attrgetter(context.environment, attribute, default=default)1172 else:1173 try:1174 name = args[2]1175 args = args[3:]
96 unmodified lines
modified:jinja2/lexer.py+21 added-6 removed
13 unmodified lines
14 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD, see LICENSE for more details.16"""17import re18from ast import literal_eval19from collections import deque20from operator import itemgetter2122from jinja2._compat import implements_iterator, intern, iteritems, text_type23from jinja2.exceptions import TemplateSyntaxError24from jinja2.utils import LRUCache2526from ast import literal_eval # to support scientific notation2728# cache for the lexers. Exists in order to be able to have multiple29# environments with the same lexer30_lexer_cache = LRUCache(50)3132# static regular expressions33whitespace_re = re.compile(r'\s+', re.U)34newline_re = re.compile(r'(\r\n|\r|\n)')35string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"36 r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)33integer_re = re.compile(r'\d+')37integer_re = re.compile(r'(\d+_)*\d+')38float_re = re.compile(39 r"""40 (?<!\.) # doesn't start with a .41 (\d+_)*\d+ # digits, possibly _ separated42 (43 (\.(\d+_)*\d+)? # optional fractional part44 e[+\-]?(\d+_)*\d+ # exponent part45 |46 \.(\d+_)*\d+ # required fractional part47 )48 """,49 re.IGNORECASE | re.VERBOSE,50)5152try:53 # check if this Python supports Unicode identifiers54 compile('föö', '<unknown>', 'eval')
13 unmodified lines
68 import jinja269 del jinja2._identifier70 del _identifier7155float_re = re.compile(r'(?<!\.)\d+\.\d+')56newline_re = re.compile(r'(\r\n|\r|\n)')5772# internal the tokens and keep references to them73TOKEN_ADD = intern('add')74TOKEN_ASSIGN = intern('assign')75TOKEN_COLON = intern('colon')
497 unmodified lines
573 except Exception as e:574 msg = str(e).split(':')[-1].strip()575 raise TemplateSyntaxError(msg, lineno, name, filename)576 elif token == 'integer':563 value = int(value)577 value = int(value.replace("_", ""))578 elif token == 'float':565 value = float(value)579 # remove all "_" first to support more Python versions580 value = literal_eval(value.replace("_", ""))581 elif token == 'operator':582 token = operators[value]583 yield Token(lineno, token, value)584
157 unmodified lines
modified:jinja2/meta.py+1 added-1 removed
27 unmodified lines
28 def enter_frame(self, frame):29 """Remember all undeclared identifiers."""30 CodeGenerator.enter_frame(self, frame)31 for _, (action, param) in iteritems(frame.symbols.loads):32 if action == 'resolve':32 if action == 'resolve' and param not in self.environment.globals:33 self.undeclared_identifiers.add(param)343536def find_undeclared_variables(ast):
70 unmodified lines
modified:jinja2/parser.py+3 added-1 removed
839 unmodified lines
840 self.stream.current.test_any('name:else', 'name:or',841 'name:and')):842 if self.stream.current.test('name:is'):843 self.fail('You cannot chain multiple tests with is')844 args = [self.parse_primary()]844 arg_node = self.parse_primary()845 arg_node = self.parse_postfix(arg_node)846 args = [arg_node]847 else:848 args = []849 node = nodes.Test(node, name, args, kwargs, dyn_args,850 dyn_kwargs, lineno=token.lineno)
57 unmodified lines
modified:jinja2/runtime.py+38 added-9 removed
56 unmodified lines
575859def new_context(environment, template_name, blocks, vars=None,60 shared=None, globals=None, locals=None):61 """Internal helper to for context creation."""61 """Internal helper for context creation."""62 if vars is None:63 vars = {}64 if shared:65 parent = vars
334 unmodified lines
400 "forgot the 'recursive' modifier.")401 return self._recurse(iterable, self._recurse, self.depth0 + 1)402403 # a nifty trick to enhance the error message if someone tried to call404 # the the loop without or with too many arguments.404 # the loop without or with too many arguments.405 __call__ = loop406 del loop407408 def __repr__(self):
90 unmodified lines
499 # This requires a bit of explanation, In the past we used to500 # decide largely based on compile-time information if a macro is501 # safe or unsafe. While there was a volatile mode it was largely502 # unused for deciding on escaping. This turns out to be503 # problemtic for macros because if a macro is safe or not not so504 # much depends on the escape mode when it was defined but when it505 # was used.503 # problematic for macros because whether a macro is safe depends not504 # on the escape mode when it was defined, but rather when it was used.505 #506 # Because however we export macros from the module system and507 # there are historic callers that do not pass an eval context (and508 # will continue to not pass one), we need to perform an instance509 # check here.510 #511 # This is considered safe because an eval context is not a valid513 # argument to callables otherwise anwyays. Worst case here is512 # argument to callables otherwise anyway. Worst case here is513 # that if no eval context is passed we fall back to the compile514 # time autoescape flag.515 if args and isinstance(args[0], EvalContext):516 autoescape = args[0].autoescape
67 unmodified lines
584585@implements_to_string586class Undefined(object):587 """The default undefined type. This undefined type can be printed and589 iterated over, but every other access will raise an :exc:`jinja2.exceptions.UndefinedError`:588 iterated over, but every other access will raise an :exc:`UndefinedError`:589590 >>> foo = Undefined(name='foo')591 >>> str(foo)592 ''
15 unmodified lines
608609 @internalcode610 def _fail_with_undefined_error(self, *args, **kwargs):611 """Regular callback function for undefined objects that raises an613 `jinja2.exceptions.UndefinedError` on call.612 `UndefinedError` on call.613 """614 if self._undefined_hint is None:615 if self._undefined_obj is missing:616 hint = '%r is undefined' % self._undefined_name
131 unmodified lines
748749 return LoggingUndefined750751752# No @implements_to_string decorator here because __str__753# is not overwritten from Undefined in this class.754# This would cause a recursion error in Python 2.755class ChainableUndefined(Undefined):756 """An undefined that is chainable, where both ``__getattr__`` and757 ``__getitem__`` return itself rather than raising an758 :exc:`UndefinedError`.759760 >>> foo = ChainableUndefined(name='foo')761 >>> str(foo.bar['baz'])762 ''763 >>> foo.bar['baz'] + 42764 Traceback (most recent call last):765 ...766 jinja2.exceptions.UndefinedError: 'foo' is undefined767768 .. versionadded:: 2.11.0769 """770 __slots__ = ()771772 def __html__(self):773 return self.__str__()774775 def __getattr__(self, _):776 return self777778 __getitem__ = __getattr__779780781@implements_to_string782class DebugUndefined(Undefined):783 """An undefined that returns the debug info when printed.784
47 unmodified lines
832833834# remove remaining slots attributes, after the metaclass did the magic they835# are unneeded and irritating as they contain wrong data for the subclasses.808del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__836del Undefined.__slots__, ChainableUndefined.__slots__, \837 DebugUndefined.__slots__, StrictUndefined.__slots__
modified:jinja2/sandbox.py+8 added-4 removed
14 unmodified lines
15import types16import operator17from jinja2.environment import Environment18from jinja2.exceptions import SecurityError19from jinja2._compat import string_types, PY2, abc19from jinja2._compat import string_types, PY2, abc, range_type20from jinja2.utils import Markup2122from markupsafe import EscapeFormatter23from string import Formatter
121 unmodified lines
145def safe_range(*args):146 """A range that can't generate ranges with a length of more than147 MAX_RANGE items.148 """149 rng = range(*args)149 rng = range_type(*args)150151 if len(rng) > MAX_RANGE:151 raise OverflowError('range too big, maximum size for range is %d' %152 MAX_RANGE)152 raise OverflowError(153 "Range too big. The sandbox blocks ranges larger than"154 " MAX_RANGE (%d)." % MAX_RANGE155 )156157 return rng158159160def unsafe(f):
328 unmodified lines
modified:jinja2/utils.py+15 added-13 removed
9 unmodified lines
10"""11import re12import json13import errno14import warnings15from collections import deque16from threading import Lock17from jinja2._compat import text_type, string_types, implements_iterator, \18 url_quote, abc
116 unmodified lines
135 try:136 if ':' in import_name:137 module, obj = import_name.split(':', 1)138 elif '.' in import_name:138 items = import_name.split('.')139 module = '.'.join(items[:-1])140 obj = items[-1]139 module, _, obj = import_name.rpartition('.')140 else:141 return __import__(import_name)142 return getattr(__import__(module, None, None, [obj]), obj)143 except (ImportError, AttributeError):
210 unmodified lines
354 def setdefault(self, key, default=None):355 """Set `default` if the key is not in the cache otherwise356 leave unchanged. Return the value of this key.357 """359 self._wlock.acquire()358 try:361 try:362 return self[key]363 except KeyError:364 self[key] = default365 return default359 return self[key]360 except KeyError:361 self[key] = default362 return default366 finally:367 self._wlock.release()363364 def clear(self):365 """Clear the cache."""366 self._wlock.acquire()
63 unmodified lines
430 del self._mapping[key]431 try:432 self._remove(key)433 except ValueError:439 # __getitem__ is not locked, it might happen434 pass435 finally:436 self._wlock.release()437
12 unmodified lines
450 return [x[1] for x in self.items()]451452 def itervalue(self):453 """Iterate over all values."""454 warnings.warn(DeprecationWarning(455 '"itervalue()" is deprecated and will be removed in version 2.12.'456 + ' Use "itervalues()" instead.'457 ), stacklevel=2)458 return self.itervalues()459460 def itervalues(self):461 """Iterate over all values."""462 return iter(self.values())463464 def keys(self):465 """Return a list of all keys ordered by most recent usage."""
7 unmodified lines
473474 __iter__ = iterkeys475476 def __reversed__(self):475 """Iterate over the values in the cache dict, oldest items477 """Iterate over the keys in the cache dict, oldest items478 coming first.479 """480 return iter(tuple(self._queue))481
163 unmodified lines
modified:tests/conftest.py+44 added-1 removed
14 unmodified lines
15from jinja2.utils import have_async_gen16from jinja2 import Environment171819def pytest_ignore_collect(path, config):19def pytest_ignore_collect(path):20 if 'async' in path.basename and not have_async_gen:21 return True22 return False232425def pytest_configure(config):26 '''Register custom marks for test categories.'''27 custom_markers = [28 'api',29 'byte_code_cache',30 'core_tags',31 'debug',32 'escapeUrlizeTarget',33 'ext',34 'extended',35 'filter',36 'for_loop',37 'helpers',38 'if_condition',39 'imports',40 'includes',41 'inheritance',42 'lexer',43 'lexnparse',44 'loaders',45 'loremIpsum',46 'lowlevel',47 'lrucache',48 'lstripblocks',49 'macros',50 'meta',51 'moduleloader',52 'parser',53 'regression',54 'sandbox',55 'set',56 'streaming',57 'syntax',58 'test_tests',59 'tokenstream',60 'undefined',61 'utils',62 'with_',63 ]64 for mark in custom_markers:65 config.addinivalue_line('markers', mark + ': test category')666768@pytest.fixture69def env():70 '''returns a new environment.71 '''
49 unmodified lines
modified:tests/test_api.py+52 added-7 removed
11 unmodified lines
12import tempfile13import shutil1415import pytest16from jinja2 import Environment, Undefined, DebugUndefined, \17 StrictUndefined, UndefinedError, meta, \16from jinja2 import Environment, Undefined, ChainableUndefined, \17 DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import Cycler
81 unmodified lines
103 assert t.render(foo='<foo>') == '&lt;foo&gt;'104 t = env.from_string('{{ foo }}')105 assert t.render(foo='<foo>') == '<foo>'106107 def test_sandbox_max_range(self, env):108 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE109110 env = SandboxedEnvironment()111 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")112113 with pytest.raises(OverflowError):114 t.render(total=MAX_RANGE + 1)115116117@pytest.mark.api118@pytest.mark.meta119class TestMeta(object):120
8 unmodified lines
129 '{% endfor %}')130 x = meta.find_undeclared_variables(ast)131 assert x == set(['bar', 'seq', 'muh'])132133 ast = env.parse('{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}')134 x = meta.find_undeclared_variables(ast)135 assert x == set(['foo'])136137 def test_find_refererenced_templates(self, env):138 ast = env.parse('{% extends "layout.html" %}{% include helper %}')139 i = meta.find_referenced_templates(ast)140 assert next(i) == 'layout.html'
81 unmodified lines
222 t = Template('A{{ test().missingattribute }}B')223 pytest.raises(UndefinedError, t.render, test=test)224225 def test_undefined_and_special_attributes(self):213 try:226 with pytest.raises(AttributeError):227 Undefined('Foo').__dict__215 except AttributeError:216 pass217 else:218 assert False, "Expected actual attribute error"228229 def test_logging_undefined(self):230 _messages = []231
33 unmodified lines
265 assert env.from_string('{{ foo.missing }}').render(foo=42) == ''266 assert env.from_string('{{ not missing }}').render() == 'True'267 pytest.raises(UndefinedError,268 env.from_string('{{ missing - 1}}').render)269 und1 = Undefined(name='x')270 und2 = Undefined(name='y')271 assert und1 == und2272 assert und1 != 42273 assert hash(und1) == hash(und2) == hash(Undefined())274 with pytest.raises(AttributeError):275 getattr(Undefined, '__slots__')276277 def test_chainable_undefined(self):278 env = Environment(undefined=ChainableUndefined)279 # The following tests are copied from test_default_undefined280 assert env.from_string('{{ missing }}').render() == u''281 assert env.from_string('{{ missing|list }}').render() == '[]'282 assert env.from_string('{{ missing is not defined }}').render() \283 == 'True'284 assert env.from_string('{{ foo.missing }}').render(foo=42) == ''285 assert env.from_string('{{ not missing }}').render() == 'True'286 pytest.raises(UndefinedError,287 env.from_string('{{ missing - 1}}').render)288 with pytest.raises(AttributeError):289 getattr(ChainableUndefined, '__slots__')290291 # The following tests ensure subclass functionality works as expected292 assert env.from_string('{{ missing.bar["baz"] }}').render() == u''293 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() \294 == u'foo'295 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(296 foo=42) == u'bar'297 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(298 foo={'bar': 42}) == u'baz'299300 def test_debug_undefined(self):301 env = Environment(undefined=DebugUndefined)302 assert env.from_string('{{ missing }}').render() == '{{ missing }}'303 pytest.raises(UndefinedError,
3 unmodified lines
307 == 'True'308 assert env.from_string('{{ foo.missing }}').render(foo=42) \309 == u"{{ no such element: int object['missing'] }}"310 assert env.from_string('{{ not missing }}').render() == 'True'311 undefined_hint = 'this is testing undefined hint of DebugUndefined'312 assert str(DebugUndefined(hint=undefined_hint)) == u'{{ undefined value printed: %s }}' % undefined_hint313 with pytest.raises(AttributeError):314 getattr(DebugUndefined, '__slots__')315316 def test_strict_undefined(self):317 env = Environment(undefined=StrictUndefined)318 pytest.raises(UndefinedError, env.from_string('{{ missing }}').render)
8 unmodified lines
327 pytest.raises(UndefinedError,328 env.from_string('{{ not missing }}').render)329 assert env.from_string('{{ missing|default("default", true) }}')\330 .render() == 'default'331 with pytest.raises(AttributeError):332 getattr(StrictUndefined, '__slots__')333334 def test_indexing_gives_undefined(self):335 t = Template("{{ var[42].foo }}")336 pytest.raises(UndefinedError, t.render, var=0)
49 unmodified lines
modified:tests/test_ext.py+8 added
238 unmodified lines
239 ext = list(env.iter_extensions())240 assert ext[0].__class__ is T1241 assert ext[1].__class__ is T2242243 def test_debug(self):244 env = Environment(extensions=['jinja2.ext.debug'])245 t = env.from_string('Hello\n{% debug %}\nGoodbye')246 out = t.render()247248 for value in ("context", "cycler", "filters", "abs", "tests", "!="):249 assert "'{}'".format(value) in out250251252@pytest.mark.ext253class TestInternationalization(object):254255 def test_trans(self):
341 unmodified lines
modified:tests/test_filters.py+105 added-13 removed
21 unmodified lines
22 def __str__(self):23 return text_type(self.value)242526@implements_to_string27class Magic2(object):28 def __init__(self, value1, value2):29 self.value1 = value130 self.value2 = value23132 def __str__(self):33 return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))343536@pytest.mark.filter37class TestFilter(object):3839 def test_filter_calling(self, env):
44 unmodified lines
84 tmpl = env.from_string('''{{ '<">&'|escape }}''')85 out = tmpl.render()86 assert out == '&lt;&#34;&gt;&amp;'8788 @pytest.mark.parametrize(89 ("chars", "expect"), [(None, "..stays.."), (".", " ..stays"), (" .", "stays")]90 )91 def test_trim(self, env, chars, expect):92 tmpl = env.from_string("{{ foo|trim(chars) }}")93 out = tmpl.render(foo=" ..stays..", chars=chars)94 assert out == expect9596 def test_striptags(self, env):97 tmpl = env.from_string('''{{ foo|striptags }}''')98 out = tmpl.render(foo=' <p>just a small \n <a href="#">'99 'example</a> link</p>\n<p>to a webpage</p> '
40 unmodified lines
140 tmpl = env.from_string('{{ foo|first }}')141 out = tmpl.render(foo=list(range(10)))142 assert out == '0'143126 def test_float(self, env):127 tmpl = env.from_string('{{ "42"|float }}|'128 '{{ "ajsghasjgd"|float }}|'129 '{{ "32.32"|float }}')130 out = tmpl.render()131 assert out == '42.0|0.0|32.32'144 @pytest.mark.parametrize(145 ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"),)146 )147 def test_float(self, env, value, expect):148 t = env.from_string("{{ '%s'|float }}" % value)149 assert t.render() == expect150151 def test_float_default(self, env):152 t = env.from_string("{{ value|float(default=1.0) }}")153 assert t.render(value="abc") == "1.0"154155 def test_format(self, env):156 tmpl = env.from_string('''{{ "%s|%s"|format("a", "b") }}''')157 out = tmpl.render()158 assert out == 'a|b'
30 unmodified lines
189 def test_indentfirst_deprecated(self, env):190 with pytest.warns(DeprecationWarning):191 env.from_string('{{ "jinja"|indent(indentfirst=true) }}').render()192193 @pytest.mark.parametrize(194 ("value", "expect"),195 (196 ("42", "42"),197 ("abc", "0"),198 ("32.32", "32"),199 ("12345678901234567890", "12345678901234567890"),200 )201 )202 def test_int(self, env, value, expect):203 t = env.from_string("{{ '%s'|int }}" % value)204 assert t.render() == expect205206 @pytest.mark.parametrize(207 ("value", "base", "expect"),208 (209 ("0x4d32", 16, "19762"),210 ("011", 8, "9"),211 ("0x33Z", 16, "0"),212 )213 )214 def test_int_base(self, env, value, base, expect):215 t = env.from_string("{{ '%s'|int(base=%d) }}" % (value, base))216 assert t.render() == expect217171 def test_int(self, env):218 def test_int_default(self, env):219 t = env.from_string("{{ value|int(default=1) }}")220 assert t.render(value="abc") == "1"221222 def test_int_special_method(self, env):223 class IntIsh(object):224 def __int__(self):225 return 42226176 tmpl = env.from_string('{{ "42"|int }}|{{ "ajsghasjgd"|int }}|'177 '{{ "32.32"|int }}|{{ "0x4d32"|int(0, 16) }}|'178 '{{ "011"|int(0, 8)}}|{{ "0x33FU"|int(0, 16) }}|'179 '{{ obj|int }}')180 out = tmpl.render(obj=IntIsh())181 assert out == '42|0|32|19762|9|0|42'227 t = env.from_string("{{ value|int }}")228 assert t.render(value=IntIsh()) == "42"229230 def test_join(self, env):231 tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')232 out = tmpl.render()
230 unmodified lines
463 def test_sort4(self, env):464 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')465 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'466467 def test_sort5(self, env):468 tmpl = env.from_string('''{{ items|sort(attribute='value.0')|join }}''')469 assert tmpl.render(items=map(Magic, [[3], [2], [4], [1]])) == '[1][2][3][4]'470471 def test_sort6(self, env):472 tmpl = env.from_string('''{{ items|sort(attribute='value1,value2')|join }}''')473 assert (tmpl.render(items=map(474 lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]))475 == '(2,1)(2,2)(2,5)(3,1)')476477 def test_sort7(self, env):478 tmpl = env.from_string('''{{ items|sort(attribute='value2,value1')|join }}''')479 assert (tmpl.render(items=map(lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)])) ==480 '(2,1)(3,1)(2,2)(2,5)')481482 def test_sort8(self, env):483 tmpl = env.from_string(484 '''{{ items|sort(attribute='value1.0,value2.0')|join }}''')485 assert (tmpl.render(items=map(486 lambda x: Magic2(x[0], x[1]),487 [([3], [1]), ([2], [2]), ([2], [1]), ([2], [5])]))488 == '([2],[1])([2],[2])([2],[5])([3],[1])')489490 def test_unique(self, env):491 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')492 assert t.render() == "bA"493
141 unmodified lines
635 env = Environment()636 tmpl = env.from_string('{{ none|map("upper")|list }}')637 assert tmpl.render() == '[]'638639 def test_map_default(self, env):640 class Fullname(object):641 def __init__(self, firstname, lastname):642 self.firstname = firstname643 self.lastname = lastname644645 class Firstname(object):646 def __init__(self, firstname):647 self.firstname = firstname648649 env = Environment()650 tmpl = env.from_string(651 '{{ users|map(attribute="lastname", default="smith")|join(", ") }}'652 )653 users = [654 Fullname("john", "lennon"),655 Fullname("jane", "edwards"),656 Fullname("jon", None),657 Firstname("mike")658 ]659 assert tmpl.render(users=users) == "lennon, edwards, None, smith"660661 def test_simple_select(self, env):662 env = Environment()663 tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')664 assert tmpl.render() == '1|3|5'
95 unmodified lines
modified:tests/test_imports.py-2 removed
137 unmodified lines
138 t = test_env.from_string('{% include [x, "header"] %}')139 test_includes(t, x='missing')140 t = test_env.from_string('{% include x %}')141 test_includes(t, x='header')142 t = test_env.from_string('{% include x %}')143 test_includes(t, x='header')142 t = test_env.from_string('{% include [x] %}')143 test_includes(t, x='header')144145 def test_include_ignoring_missing(self, test_env):
33 unmodified lines
modified:tests/test_lexnparse.py+33 added-3 removed
334 unmodified lines
335 def test_inop(self, env):336 tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')337 assert tmpl.render() == 'True|False'338339 def test_literals(self, env):340 tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}')341 assert tmpl.render().lower() == '[]|{}|()'339 @pytest.mark.parametrize("value", ("[]", "{}", "()"))340 def test_collection_literal(self, env, value):341 t = env.from_string("{{ %s }}" % value)342 assert t.render() == value343344 @pytest.mark.parametrize(345 ("value", "expect"),346 (347 ("1", "1"),348 ("123", "123"),349 ("12_34_56", "123456"),350 ("1.2", "1.2"),351 ("34.56", "34.56"),352 ("3_4.5_6", "34.56"),353 ("1e0", "1.0"),354 ("10e1", "100.0"),355 ("2.5e100", "2.5e+100"),356 ("2.5e+100", "2.5e+100"),357 ("25.6e-10", "2.56e-09"),358 ("1_2.3_4e5_6", "1.234e+57"),359 )360 )361 def test_numeric_literal(self, env, value, expect):362 t = env.from_string("{{ %s }}" % value)363 assert t.render() == expect364365 def test_bool(self, env):366 tmpl = env.from_string('{{ true and false }}|{{ false '367 'or true }}|{{ not false }}')368 assert tmpl.render() == 'False|True|True'
155 unmodified lines
524 env = Environment(lstrip_blocks=True, trim_blocks=False)525 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')526 assert tmpl.render() == " \n "527528 def test_lstrip_blocks_false_with_no_lstrip(self, env):529 # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False530 env = Environment(lstrip_blocks=False, trim_blocks=False)531 tmpl = env.from_string(''' {% if True %}\n {% endif %}''')532 assert tmpl.render() == " \n "533 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')534 assert tmpl.render() == " \n "535536 def test_lstrip_endline(self, env):537 env = Environment(lstrip_blocks=True, trim_blocks=False)538 tmpl = env.from_string(539 ''' hello{% if True %}\n goodbye{% endif %}''')
148 unmodified lines
modified:tests/test_regression.py+9 added
481 unmodified lines
482 def test_empty_if(self, env):483 t = env.from_string('{% if foo %}{% else %}42{% endif %}')484 assert t.render(foo=False) == '42'485486 def test_subproperty_if(self, env):487 t = env.from_string('{% if object1.subproperty1 is eq object2.subproperty2 %}42{% endif %}')488 assert t.render(object1={'subproperty1': 'value'}, object2={'subproperty2': 'value'}) == '42'489490 def test_set_and_include(self):491 env = Environment(loader=DictLoader({492 'inc': 'bar',493 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}'
48 unmodified lines
542 tmpl = env.from_string('''543 {%- for value in values recursive %}1{% else %}0{% endfor -%}544 ''')545 assert tmpl.render(values=[]) == '0'546547 def test_markup_and_chainable_undefined(self):548 from jinja2 import Markup549 from jinja2.runtime import ChainableUndefined550 assert str(Markup(ChainableUndefined())) == ''
modified:tests/test_security.py+2 added-10 removed
138 unmodified lines
139 t = env.from_string('{{ %s }}' % expr)140 assert t.render(ctx) == rv141 env.intercepted_binops = frozenset(['+'])142 t = env.from_string('{{ %s }}' % expr)143 try:143 with pytest.raises(TemplateRuntimeError):144 t.render(ctx)145 except TemplateRuntimeError as e:146 pass147 else:148 assert False, 'expected runtime error'145146 def test_unary_operator_intercepting(self, env):147 def disable_op(arg):148 raise TemplateRuntimeError('that operator so does not work')
3 unmodified lines
152 t = env.from_string('{{ %s }}' % expr)153 assert t.render(ctx) == rv154 env.intercepted_unops = frozenset(['-'])155 t = env.from_string('{{ %s }}' % expr)160 try:156 with pytest.raises(TemplateRuntimeError):157 t.render(ctx)162 except TemplateRuntimeError as e:163 pass164 else:165 assert False, 'expected runtime error'158159160@pytest.mark.sandbox161class TestStringFormat(object):
39 unmodified lines
modified:tests/test_utils.py+116 added-4 removed
6 unmodified lines
78 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""1112from collections import deque13import gc14import pickle15import random1617import pytest1815import pickle1619from jinja2._compat import string_types, range_type20from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18 select_autoescape21 select_autoescape, generate_lorem_ipsum, missing, consume22from markupsafe import Markup232024@pytest.mark.utils25@pytest.mark.lrucache26class TestLRUCache(object):27
6 unmodified lines
34 d["d"] = 435 assert len(d) == 336 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d3738 def test_itervalue_deprecated(self):39 cache = LRUCache(3)40 cache["a"] = 141 cache["b"] = 242 with pytest.deprecated_call():43 cache.itervalue()4445 def test_itervalues(self):46 cache = LRUCache(3)47 cache["b"] = 148 cache["a"] = 249 values = [v for v in cache.itervalues()]50 assert len(values) == 251 assert 1 in values52 assert 2 in values5354 def test_itervalues_empty(self):55 cache = LRUCache(2)56 values = [v for v in cache.itervalues()]57 assert len(values) == 05859 def test_pickleable(self):60 cache = LRUCache(2)61 cache["foo"] = 4262 cache["bar"] = 23
4 unmodified lines
67 assert copy.capacity == cache.capacity68 assert copy._mapping == cache._mapping69 assert copy._queue == cache._queue7071 def test_clear(self):72 d = LRUCache(3)73 d["a"] = 174 d["b"] = 275 d["c"] = 376 d.clear()77 assert d.__getstate__() == {'capacity': 3, '_mapping': {}, '_queue': deque([])}7879 def test_repr(self):80 d = LRUCache(3)81 d["a"] = 182 d["b"] = 283 d["c"] = 384 # Sort the strings - mapping is unordered85 assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>")8687 def test_items(self):88 """Test various items, keys, values and iterators of LRUCache."""89 d = LRUCache(3)90 d["a"] = 191 d["b"] = 292 d["c"] = 393 assert d.items() == list(d.iteritems()) == [('c', 3), ('b', 2), ('a', 1)]94 assert d.keys() == list(d.iterkeys()) == ['c', 'b', 'a']95 assert d.values() == list(d.itervalues()) == [3, 2, 1]96 assert list(reversed(d)) == ['a', 'b', 'c']9798 # Change the cache a little99 d["b"]100 d["a"] = 4101 assert d.items() == list(d.iteritems()) == [('a', 4), ('b', 2), ('c', 3)]102 assert d.keys() == list(d.iterkeys()) == ['a', 'b', 'c']103 assert d.values() == list(d.itervalues()) == [4, 2, 3]104 assert list(reversed(d)) == ['c', 'b', 'a']105106 def test_setdefault(self):107 d = LRUCache(3)108 assert len(d) == 0109 assert d.setdefault("a") is None110 assert d.setdefault("a", 1) is None111 assert len(d) == 1112 assert d.setdefault("b", 2) == 2113 assert len(d) == 2114115116@pytest.mark.utils117@pytest.mark.helpers118class TestHelpers(object):119
31 unmodified lines
151 target = "<script>"152 assert urlize(url, target=target) == ('<a href="http://example.org"'153 ' target="&lt;script&gt;">'154 'http://example.org</a>')155156157@pytest.mark.utils158@pytest.mark.loremIpsum159class TestLoremIpsum(object):160 def test_lorem_ipsum_markup(self):161 """Test that output of lorem_ipsum is Markup by default."""162 assert isinstance(generate_lorem_ipsum(), Markup)163164 def test_lorem_ipsum_html(self):165 """Test that output of lorem_ipsum is a string_type when not html."""166 assert isinstance(generate_lorem_ipsum(html=False), string_types)167168 def test_lorem_ipsum_n(self):169 """Test that the n (number of lines) works as expected."""170 assert generate_lorem_ipsum(n=0, html=False) == u''171 for n in range_type(1, 50):172 assert generate_lorem_ipsum(n=n, html=False).count('\n') == (n - 1) * 2173174 def test_lorem_ipsum_min(self):175 """Test that at least min words are in the output of each line"""176 for _ in range_type(5):177 m = random.randrange(20, 99)178 for _ in range_type(10):179 assert generate_lorem_ipsum(n=1, min=m, html=False).count(' ') >= m - 1180181 def test_lorem_ipsum_max(self):182 """Test that at least max words are in the output of each line"""183 for _ in range_type(5):184 m = random.randrange(21, 100)185 for _ in range_type(10):186 assert generate_lorem_ipsum(n=1, max=m, html=False).count(' ') < m - 1187188189def test_missing():190 """Test the repr of missing."""191 assert repr(missing) == u'missing'192193def test_consume():194 """Test that consume consumes an iterator."""195 x = iter([1, 2, 3, 4, 5])196 consume(x)197 with pytest.raises(StopIteration):198 next(x)
added:.azure-pipelines.yml+61 added
1trigger:2 - master3 - '*.x'45variables:6 vmImage: ubuntu-latest7 python.version: 3.78 TOXENV: py,coverage-ci9 hasTestResults: true1011strategy:12 matrix:13 Python 3.7 Linux:14 vmImage: ubuntu-latest15 Python 3.7 Windows:16 vmImage: windows-latest17 Python 3.7 Mac:18 vmImage: macos-latest19 PyPy 3 Linux:20 python.version: pypy321 Python 3.6 Linux:22 python.version: 3.623 Python 3.5 Linux:24 python.version: 3.525 Python 2.7 Linux:26 python.version: 2.727 Python 2.7 Windows:28 python.version: 2.729 vmImage: windows-latest30 Docs:31 TOXENV: docs-html32 hasTestResults: false3334pool:35 vmImage: $[ variables.vmImage ]3637steps:38 - task: UsePythonVersion@039 inputs:40 versionSpec: $(python.version)41 displayName: Use Python $(python.version)4243 - script: pip --disable-pip-version-check install -U tox44 displayName: Install tox4546 - script: tox -s false -- --junit-xml=test-results.xml47 displayName: Run tox4849 - task: PublishTestResults@250 inputs:51 testResultsFiles: test-results.xml52 testRunTitle: $(Agent.JobName)53 condition: eq(variables['hasTestResults'], 'true')54 displayName: Publish test results5556 - task: PublishCodeCoverageResults@157 inputs:58 codeCoverageTool: Cobertura59 summaryFileLocation: coverage.xml60 condition: eq(variables['hasTestResults'], 'true')61 displayName: Publish coverage results
deleted:.coveragerc-11 removed
1[run]2branch = True3source =4 jinja25 tests67[paths]8source =9 jinja210 .tox/*/lib/python*/site-packages/jinja211 .tox/pypy/site-packages/jinja2
modified:.gitignore+1 added
8 unmodified lines
9.DS_Store10.tox/11.cache/12.idea/13env/14venv/15venv-*/16.coverage17.coverage.*
2 unmodified lines
deleted:.travis.yml-46 removed
1dist: xenial2sudo: false3language: python45python:6 - 3.77 - 3.68 - 3.59 - 3.410 - 2.711 - pypy3.5-6.012 - pypy2.7-6.01314env:15 - TOXENV=py,codecov1617matrix:18 include:19 - python: nightly20 env: TOXENV=py21 - python: 3.622 env: TOXENV=docs-html2324install:25 - pip install tox2627script:28 - tox2930cache:31 - pip3233branches:34 only:35 - master36 - /^.*-maintenance$/3738notifications:39 email: false40 irc:41 channels:42 - "chat.freenode.net#pocoo"43 on_success: change44 on_failure: always45 use_notice: true46 skip_join: true
deleted:AUTHORS-35 removed
1Jinja is written and maintained by the Jinja Team and various2contributors:34Lead Developer:56- Armin Ronacher <armin.ronacher@active-4.com>78Developers:910- Christoph Hack11- Georg Brandl1213Contributors:1415- Bryan McLemore16- Mickaël Guérin <kael@crocobox.org>17- Cameron Knight18- Lawrence Journal-World.19- David Cramer20- Adrian Mönnich (ThiefMaster)2122Patches and suggestions:2324- Ronny Pfannschmidt25- Axel Böhm26- Alexey Melchakov27- Bryan McLemore28- Clovis Fabricio (nosklo)29- Cameron Knight30- Peter van Dijk (Habbie)31- Stefan Ebner32- Rene Leonhardt33- Thomas Waldmann34- Cory Benfield (Lukasa)35- Florian Bruhin (The-Compiler)
modified:CHANGES.rst+460 added-420 removed
1.. currentmodule:: jinja223Jinja Changelog4===============563Version 2.114------------510unreleased6Unreleased712- Async support is only loaded the first time an13 :class:`~environment.Environment` enables it, in order to avoid a14 slow initial import. (`#765`_)15- Python 2.6 and 3.3 are not supported anymore.16- The `map` filter in async mode now automatically awaits8- Async support is only loaded the first time an9 :class:`~environment.Environment` enables it, in order to avoid a10 slow initial import. :issue:`765`11- Python 2.6 and 3.3 are not supported anymore.12- The ``map`` filter in async mode now automatically awaits13- Added a new ``ChainableUndefined`` class to support getitem and14 getattr on an undefined object. :issue:`977`15- Allow ``{%+`` syntax (with NOP behavior) when ``lstrip_blocks`` is16 disabled. :issue:`748`17- Added a ``default`` parameter for the ``map`` filter. :issue:`557`18- Exclude environment globals from19 :func:`meta.find_undeclared_variables`. :issue:`931`20- Float literals can be written with scientific notation, like21 2.56e-3. :issue:`912`, :pr:`922`22- Int and float literals can be written with the '_' separator for23 legibility, like 12_345. :pr:`923`24- Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`25- The ``trim`` filter takes an optional string of characters to trim.26 :pr:`828`27- A new ``jinja2.ext.debug`` extension adds a ``{% debug %}`` tag to28 quickly dump the current context and available filters and tests.29 :issue:`174`, :pr:`798, 983`3018.. _#765: https://github.com/pallets/jinja/issues/7653132Version 2.10.333--------------3435Released 2019-10-043637- Fix a typo in Babel entry point in ``setup.py`` that was preventing38 installation.394041Version 2.10.242--------------4344Released 2019-10-044546- Fix Python 3.7 deprecation warnings.47- Using ``range`` in the sandboxed environment uses ``xrange`` on48 Python 2 to avoid memory use. :issue:`933`49- Use Python 3.7's better traceback support to avoid a core dump when50 using debug builds of Python 3.7. :issue:`1050`515253Version 2.10.154--------------5556Released 2019-04-06
5 unmodified lines
6263Version 2.1064------------6534released on November 8th 201766Released 2017-11-086736- Added a new extension node called ``OverlayScope`` which can be used to37 create an unoptimized scope that will look up all variables from a38 derived context.39- Added an ``in`` test that works like the in operator. This can be used40 in combination with ``reject`` and ``select``.41- Added ``previtem`` and ``nextitem`` to loop contexts, providing access to the42 previous/next item in the loop. If such an item does not exist, the value is43 undefined.44- Added ``changed(*values)`` to loop contexts, providing an easy way of45 checking whether a value has changed since the last iteration (or rather46 since the last call of the method)47- Added a ``namespace`` function that creates a special object which allows48 attribute assignment using the ``set`` tag. This can be used to carry data49 across scopes, e.g. from a loop body to code that comes after the loop.50- Added a ``trimmed`` modifier to ``{% trans %}`` to strip linebreaks and51 surrounding whitespace. Also added a new policy to enable this for all52 ``trans`` blocks.53- The ``random`` filter is no longer incorrectly constant folded and will54 produce a new random choice each time the template is rendered. (`#478`_)55- Added a ``unique`` filter. (`#469`_)56- Added ``min`` and ``max`` filters. (`#475`_)57- Added tests for all comparison operators: ``eq``, ``ne``, ``lt``, ``le``,58 ``gt``, ``ge``. (`#665`_)59- ``import`` statement cannot end with a trailing comma. (`#617`_, `#618`_)60- ``indent`` filter will not indent blank lines by default. (`#685`_)61- Add ``reverse`` argument for ``dictsort`` filter. (`#692`_)62- Add a ``NativeEnvironment`` that renders templates to native Python types63 instead of strings. (`#708`_)64- Added filter support to the block ``set`` tag. (`#489`_)65- ``tojson`` filter marks output as safe to match documented behavior.66 (`#718`_)67- Resolved a bug where getting debug locals for tracebacks could68 modify template context.69- Fixed a bug where having many ``{% elif ... %}`` blocks resulted in a70 "too many levels of indentation" error. These blocks now compile to71 native ``elif ..:`` instead of ``else: if ..:`` (`#759`_)68- Added a new extension node called ``OverlayScope`` which can be used69 to create an unoptimized scope that will look up all variables from70 a derived context.71- Added an ``in`` test that works like the in operator. This can be72 used in combination with ``reject`` and ``select``.73- Added ``previtem`` and ``nextitem`` to loop contexts, providing74 access to the previous/next item in the loop. If such an item does75 not exist, the value is undefined.76- Added ``changed(*values)`` to loop contexts, providing an easy way77 of checking whether a value has changed since the last iteration (or78 rather since the last call of the method)79- Added a ``namespace`` function that creates a special object which80 allows attribute assignment using the ``set`` tag. This can be used81 to carry data across scopes, e.g. from a loop body to code that82 comes after the loop.83- Added a ``trimmed`` modifier to ``{% trans %}`` to strip linebreaks84 and surrounding whitespace. Also added a new policy to enable this85 for all ``trans`` blocks.86- The ``random`` filter is no longer incorrectly constant folded and87 will produce a new random choice each time the template is rendered.88 :pr:`478`89- Added a ``unique`` filter. :pr:`469`90- Added ``min`` and ``max`` filters. :pr:`475`91- Added tests for all comparison operators: ``eq``, ``ne``, ``lt``,92 ``le``, ``gt``, ``ge``. :pr:`665`93- ``import`` statement cannot end with a trailing comma. :pr:`617`,94 :pr:`618`95- ``indent`` filter will not indent blank lines by default. :pr:`685`96- Add ``reverse`` argument for ``dictsort`` filter. :pr:`692`97- Add a ``NativeEnvironment`` that renders templates to native Python98 types instead of strings. :pr:`708`99- Added filter support to the block ``set`` tag. :pr:`489`100- ``tojson`` filter marks output as safe to match documented behavior.101 :pr:`718`102- Resolved a bug where getting debug locals for tracebacks could103 modify template context.104- Fixed a bug where having many ``{% elif ... %}`` blocks resulted in105 a "too many levels of indentation" error. These blocks now compile106 to native ``elif ..:`` instead of ``else: if ..:`` :issue:`759`10773.. _#469: https://github.com/pallets/jinja/pull/46974.. _#475: https://github.com/pallets/jinja/pull/47575.. _#478: https://github.com/pallets/jinja/pull/47876.. _#489: https://github.com/pallets/jinja/pull/48977.. _#617: https://github.com/pallets/jinja/pull/61778.. _#618: https://github.com/pallets/jinja/pull/61879.. _#665: https://github.com/pallets/jinja/pull/66580.. _#685: https://github.com/pallets/jinja/pull/68581.. _#692: https://github.com/pallets/jinja/pull/69282.. _#708: https://github.com/pallets/jinja/pull/70883.. _#718: https://github.com/pallets/jinja/pull/71884.. _#759: https://github.com/pallets/jinja/pull/75910886109Version 2.9.6110-------------11190(bugfix release, released on April 3rd 2017)112Released 2017-04-0311392- Fixed custom context behavior in fast resolve mode (#675)114- Fixed custom context behavior in fast resolve mode :issue:`675`115116117Version 2.9.5118-------------11998(bugfix release, released on January 28th 2017)120Released 2017-01-28121100- Restored the original repr of the internal ``_GroupTuple`` because this101 caused issues with ansible and it was an unintended change. (#654)102- Added back support for custom contexts that override the old ``resolve``103 method since it was hard for people to spot that this could cause a104 regression.105- Correctly use the buffer for the else block of for loops. This caused106 invalid syntax errors to be caused on 2.x and completely wrong behavior107 on Python 3 (#669)108- Resolve an issue where the ``{% extends %}`` tag could not be used with109 async environments. (#668)110- Reduce memory footprint slightly by reducing our unicode database dump111 we use for identifier matching on Python 3 (#666)112- Fixed autoescaping not working for macros in async compilation mode. (#671)122- Restored the original repr of the internal ``_GroupTuple`` because123 this caused issues with ansible and it was an unintended change.124 :issue:`654`125- Added back support for custom contexts that override the old126 ``resolve`` method since it was hard for people to spot that this127 could cause a regression.128- Correctly use the buffer for the else block of for loops. This129 caused invalid syntax errors to be caused on 2.x and completely130 wrong behavior on Python 3 :issue:`669`131- Resolve an issue where the ``{% extends %}`` tag could not be used132 with async environments. :issue:`668`133- Reduce memory footprint slightly by reducing our unicode database134 dump we use for identifier matching on Python 3 :issue:`666`135- Fixed autoescaping not working for macros in async compilation mode.136 :issue:`671`137138139Version 2.9.4140-------------141118(bugfix release, released on January 10th 2017)142Released 2017-01-10143120- Solved some warnings for string literals. (#646)121- Increment the bytecode cache version which was not done due to an122 oversight before.123- Corrected bad code generation and scoping for filtered loops. (#649)124- Resolved an issue where top-level output silencing after known extend125 blocks could generate invalid code when blocks where contained in if126 statements. (#651)127- Made the ``truncate.leeway`` default configurable to improve compatibility128 with older templates.144- Solved some warnings for string literals. :issue:`646`145- Increment the bytecode cache version which was not done due to an146 oversight before.147- Corrected bad code generation and scoping for filtered loops.148 :issue:`649`149- Resolved an issue where top-level output silencing after known150 extend blocks could generate invalid code when blocks where151 contained in if statements. :issue:`651`152- Made the ``truncate.leeway`` default configurable to improve153 compatibility with older templates.154155156Version 2.9.3157-------------158134(bugfix release, released on January 8th 2017)159Released 2017-01-08160136- Restored the use of blocks in macros to the extend that was possible137 before. On Python 3 it would render a generator repr instead of138 the block contents. (#645)139- Set a consistent behavior for assigning of variables in inner scopes140 when the variable is also read from an outer scope. This now sets the141 intended behavior in all situations however it does not restore the142 old behavior where limited assignments to outer scopes was possible.143 For more information and a discussion see #641144- Resolved an issue where ``block scoped`` would not take advantage of the145 new scoping rules. In some more exotic cases a variable overridden in a146 local scope would not make it into a block.147- Change the code generation of the ``with`` statement to be in line with the148 new scoping rules. This resolves some unlikely bugs in edge cases. This149 also introduces a new internal ``With`` node that can be used by extensions.161- Restored the use of blocks in macros to the extend that was possible162 before. On Python 3 it would render a generator repr instead of the163 block contents. :issue:`645`164- Set a consistent behavior for assigning of variables in inner scopes165 when the variable is also read from an outer scope. This now sets166 the intended behavior in all situations however it does not restore167 the old behavior where limited assignments to outer scopes was168 possible. For more information and a discussion see :issue:`641`169- Resolved an issue where ``block scoped`` would not take advantage of170 the new scoping rules. In some more exotic cases a variable171 overriden in a local scope would not make it into a block.172- Change the code generation of the ``with`` statement to be in line173 with the new scoping rules. This resolves some unlikely bugs in edge174 cases. This also introduces a new internal ``With`` node that can be175 used by extensions.176177178Version 2.9.2179-------------180155(bugfix release, released on January 8th 2017)181Released 2017-01-08182157- Fixed a regression that caused for loops to not be able to use the same158 variable for the target as well as source iterator. (#640)159- Add support for a previously unknown behavior of macros. It used to be160 possible in some circumstances to explicitly provide a caller argument161 to macros. While badly buggy and unintended it turns out that this is a162 common case that gets copy pasted around. To not completely break backwards163 compatibility with the most common cases it's now possible to provide an164 explicit keyword argument for caller if it's given an explicit default.165 (#642)183- Fixed a regression that caused for loops to not be able to use the184 same variable for the target as well as source iterator.185 :issue:`640`186- Add support for a previously unknown behavior of macros. It used to187 be possible in some circumstances to explicitly provide a caller188 argument to macros. While badly buggy and unintended it turns out189 that this is a common case that gets copy pasted around. To not190 completely break backwards compatibility with the most common cases191 it's now possible to provide an explicit keyword argument for caller192 if it's given an explicit default. :issue:`642`193194195Version 2.9.1196-------------197171(bugfix release, released on January 7th 2017)198Released 2017-01-07199173- Resolved a regression with call block scoping for macros. Nested caller174 blocks that used the same identifiers as outer macros could refer to the175 wrong variable incorrectly.200- Resolved a regression with call block scoping for macros. Nested201 caller blocks that used the same identifiers as outer macros could202 refer to the wrong variable incorrectly.203204205Version 2.9206-----------180(codename Derivation, released on January 7th 2017)207182- Change cache key definition in environment. This fixes a performance183 regression introduced in 2.8.184- Added support for ``generator_stop`` on supported Python versions185 (Python 3.5 and later)186- Corrected a long standing issue with operator precedence of math operations187 not being what was expected.188- Added support for Python 3.6 async iterators through a new async mode.189- Added policies for filter defaults and similar things.190- urlize now sets "rel noopener" by default.191- Support attribute fallback for old-style classes in 2.x.192- Support toplevel set statements in extend situations.193- Restored behavior of Cycler for Python 3 users.194- Subtraction now follows the same behavior as other operators on undefined195 values.196- ``map`` and friends will now give better error messages if you forgot to197 quote the parameter.198- Depend on MarkupSafe 0.23 or higher.199- Improved the ``truncate`` filter to support better truncation in case200 the string is barely truncated at all.201- Change the logic for macro autoescaping to be based on the runtime202 autoescaping information at call time instead of macro define time.203- Ported a modified version of the ``tojson`` filter from Flask to Jinja2204 and hooked it up with the new policy framework.205- Block sets are now marked ``safe`` by default.206- On Python 2 the asciification of ASCII strings can now be disabled with207 the ``compiler.ascii_str`` policy.208- Tests now no longer accept an arbitrary expression as first argument but209 a restricted one. This means that you can now properly use multiple210 tests in one expression without extra parentheses. In particular you can211 now write ``foo is divisibleby 2 or foo is divisibleby 3``212 as you would expect.213- Greatly changed the scoping system to be more consistent with what template214 designers and developers expect. There is now no more magic difference215 between the different include and import constructs. Context is now always216 propagated the same way. The only remaining differences is the defaults217 for ``with context`` and ``without context``.218- The ``with`` and ``autoescape`` tags are now built-in.219- Added the new ``select_autoescape`` function which helps configuring better220 autoescaping easier.221- Fixed a runtime error in the sandbox when attributes of async generators222 were accessed.208Released 2017-01-07, codename Derivation209210- Change cache key definition in environment. This fixes a performance211 regression introduced in 2.8.212- Added support for ``generator_stop`` on supported Python versions213 (Python 3.5 and later)214- Corrected a long standing issue with operator precedence of math215 operations not being what was expected.216- Added support for Python 3.6 async iterators through a new async217 mode.218- Added policies for filter defaults and similar things.219- Urlize now sets "rel noopener" by default.220- Support attribute fallback for old-style classes in 2.x.221- Support toplevel set statements in extend situations.222- Restored behavior of Cycler for Python 3 users.223- Subtraction now follows the same behavior as other operators on224 undefined values.225- ``map`` and friends will now give better error messages if you226 forgot to quote the parameter.227- Depend on MarkupSafe 0.23 or higher.228- Improved the ``truncate`` filter to support better truncation in229 case the string is barely truncated at all.230- Change the logic for macro autoescaping to be based on the runtime231 autoescaping information at call time instead of macro define time.232- Ported a modified version of the ``tojson`` filter from Flask to233 Jinja2 and hooked it up with the new policy framework.234- Block sets are now marked ``safe`` by default.235- On Python 2 the asciification of ASCII strings can now be disabled236 with the ``compiler.ascii_str`` policy.237- Tests now no longer accept an arbitrary expression as first argument238 but a restricted one. This means that you can now properly use239 multiple tests in one expression without extra parentheses. In240 particular you can now write ``foo is divisibleby 2 or foo is241 divisibleby 3`` as you would expect.242- Greatly changed the scoping system to be more consistent with what243 template designers and developers expect. There is now no more magic244 difference between the different include and import constructs.245 Context is now always propagated the same way. The only remaining246 differences is the defaults for ``with context`` and ``without247 context``.248- The ``with`` and ``autoescape`` tags are now built-in.249- Added the new ``select_autoescape`` function which helps configuring250 better autoescaping easier.251- Fixed a runtime error in the sandbox when attributes of async252 generators were accessed.253254255Version 2.8.1256-------------257228(bugfix release, released on December 29th 2016)258Released 2016-12-29259230- Fixed the ``for_qs`` flag for ``urlencode``.231- Fixed regression when applying ``int`` to non-string values.232- SECURITY: if the sandbox mode is used format expressions are now sandboxed233 with the same rules as in Jinja. This solves various information leakage234 problems that can occur with format strings.260- Fixed the ``for_qs`` flag for ``urlencode``.261- Fixed regression when applying ``int`` to non-string values.262- SECURITY: if the sandbox mode is used format expressions are now263 sandboxed with the same rules as in Jinja. This solves various264 information leakage problems that can occur with format strings.265266267Version 2.8268-----------269240(codename Replacement, released on July 26th 2015)270Released 2015-07-26, codename Replacement271242- Added ``target`` parameter to urlize function.243- Added support for ``followsymlinks`` to the file system loader.244- The truncate filter now counts the length.245- Added equalto filter that helps with select filters.246- Changed cache keys to use absolute file names if available247 instead of load names.248- Fixed loop length calculation for some iterators.249- Changed how Jinja2 enforces strings to be native strings in250 Python 2 to work when people break their default encoding.251- Added :func:`make_logging_undefined` which returns an undefined252 object that logs failures into a logger.253- If unmarshalling of cached data fails the template will be254 reloaded now.255- Implemented a block ``set`` tag.256- Default cache size was increased to 400 from a low 50.257- Fixed ``is number`` test to accept long integers in all Python versions.258- Changed ``is number`` to accept Decimal as a number.259- Added a check for default arguments followed by non-default arguments. This260 change makes ``{% macro m(x, y=1, z) %}...{% endmacro %}`` a syntax error.261 The previous behavior for this code was broken anyway (resulting in the262 default value being applied to ``y``).263- Add ability to use custom subclasses of ``jinja2.compiler.CodeGenerator`` and264 ``jinja2.runtime.Context`` by adding two new attributes to the environment265 (``code_generator_class`` and ``context_class``) (pull request ``#404``).266- added support for context/environment/evalctx decorator functions on267 the finalize callback of the environment.268- escape query strings for urlencode properly. Previously slashes were not269 escaped in that place.270- Add 'base' parameter to 'int' filter.272- Added ``target`` parameter to urlize function.273- Added support for ``followsymlinks`` to the file system loader.274- The truncate filter now counts the length.275- Added equalto filter that helps with select filters.276- Changed cache keys to use absolute file names if available instead277 of load names.278- Fixed loop length calculation for some iterators.279- Changed how Jinja2 enforces strings to be native strings in Python 2280 to work when people break their default encoding.281- Added :func:`make_logging_undefined` which returns an undefined282 object that logs failures into a logger.283- If unmarshalling of cached data fails the template will be reloaded284 now.285- Implemented a block ``set`` tag.286- Default cache size was increased to 400 from a low 50.287- Fixed ``is number`` test to accept long integers in all Python288 versions.289- Changed ``is number`` to accept Decimal as a number.290- Added a check for default arguments followed by non-default291 arguments. This change makes ``{% macro m(x, y=1, z) %}`` a syntax292 error. The previous behavior for this code was broken anyway293 (resulting in the default value being applied to ``y``).294- Add ability to use custom subclasses of295 ``jinja2.compiler.CodeGenerator`` and ``jinja2.runtime.Context`` by296 adding two new attributes to the environment297 (``code_generator_class`` and ``context_class``) (pull request298 ``:issue:`404```).299- Added support for context/environment/evalctx decorator functions on300 the finalize callback of the environment.301- Escape query strings for urlencode properly. Previously slashes were302 not escaped in that place.303- Add 'base' parameter to 'int' filter.304305306Version 2.7.3307-------------308276(bugfix release, released on June 6th 2014)309Released 2014-06-06310278- Security issue: Corrected the security fix for the cache folder. This279 fix was provided by RedHat.311- Security issue: Corrected the security fix for the cache folder.312 This fix was provided by RedHat.313314315Version 2.7.2316-------------317285(bugfix release, released on January 10th 2014)318Released 2014-01-10319287- Prefix loader was not forwarding the locals properly to288 inner loaders. This is now fixed.289- Security issue: Changed the default folder for the filesystem cache to be290 user specific and read and write protected on UNIX systems. See291 `Debian bug 734747`_ for more information.320- Prefix loader was not forwarding the locals properly to inner321 loaders. This is now fixed.322- Security issue: Changed the default folder for the filesystem cache323 to be user specific and read and write protected on UNIX systems.324 See `Debian bug 734747`_ for more information.325293.. _Debian bug 734747: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734747326.. _Debian bug 734747: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734747327328329Version 2.7.1330-------------331299(bugfix release, released on August 7th 2013)332Released 2013-08-07333301- Fixed a bug with ``call_filter`` not working properly on environment302 and context filters.303- Fixed lack of Python 3 support for bytecode caches.304- Reverted support for defining blocks in included templates as this305 broke existing templates for users.306- Fixed some warnings with hashing of undefineds and nodes if Python307 is run with warnings for Python 3.308- Added support for properly hashing undefined objects.309- Fixed a bug with the title filter not working on already uppercase310 strings.334- Fixed a bug with ``call_filter`` not working properly on environment335 and context filters.336- Fixed lack of Python 3 support for bytecode caches.337- Reverted support for defining blocks in included templates as this338 broke existing templates for users.339- Fixed some warnings with hashing of undefineds and nodes if Python340 is run with warnings for Python 3.341- Added support for properly hashing undefined objects.342- Fixed a bug with the title filter not working on already uppercase343 strings.344345346Version 2.7347-----------348316(codename Translation, released on May 20th 2013)349Released 2013-05-20, codename Translation350318- Choice and prefix loaders now dispatch source and template lookup319 separately in order to work in combination with module loaders as320 advertised.321- Fixed filesizeformat.322- Added a non-silent option for babel extraction.323- Added ``urlencode`` filter that automatically quotes values for324 URL safe usage with utf-8 as only supported encoding. If applications325 want to change this encoding they can override the filter.326- Added ``keep-trailing-newline`` configuration to environments and327 templates to optionally preserve the final trailing newline.328- Accessing ``last`` on the loop context no longer causes the iterator329 to be consumed into a list.330- Python requirement changed: 2.6, 2.7 or >= 3.3 are required now,331 supported by same source code, using the "six" compatibility library.332- Allow ``contextfunction`` and other decorators to be applied to ``__call__``.333- Added support for changing from newline to different signs in the ``wordwrap``334 filter.335- Added support for ignoring memcache errors silently.336- Added support for keeping the trailing newline in templates.337- Added finer grained support for stripping whitespace on the left side338 of blocks.339- Added ``map``, ``select``, ``reject``, ``selectattr`` and ``rejectattr``340 filters.341- Added support for ``loop.depth`` to figure out how deep inside a recursive342 loop the code is.343- Disabled py_compile for pypy and python 3.351- Choice and prefix loaders now dispatch source and template lookup352 separately in order to work in combination with module loaders as353 advertised.354- Fixed filesizeformat.355- Added a non-silent option for babel extraction.356- Added ``urlencode`` filter that automatically quotes values for URL357 safe usage with utf-8 as only supported encoding. If applications358 want to change this encoding they can override the filter.359- Added ``keep-trailing-newline`` configuration to environments and360 templates to optionally preserve the final trailing newline.361- Accessing ``last`` on the loop context no longer causes the iterator362 to be consumed into a list.363- Python requirement changed: 2.6, 2.7 or >= 3.3 are required now,364 supported by same source code, using the "six" compatibility365 library.366- Allow ``contextfunction`` and other decorators to be applied to367 ``__call__``.368- Added support for changing from newline to different signs in the369 ``wordwrap`` filter.370- Added support for ignoring memcache errors silently.371- Added support for keeping the trailing newline in templates.372- Added finer grained support for stripping whitespace on the left373 side of blocks.374- Added ``map``, ``select``, ``reject``, ``selectattr`` and375 ``rejectattr`` filters.376- Added support for ``loop.depth`` to figure out how deep inside a377 recursive loop the code is.378- Disabled py_compile for pypy and python 3.379380381Version 2.6382-----------383349(codename Convolution, released on July 24th 2011)384Released 2011-07-24, codename Convolution385351- internal attributes now raise an internal attribute error now instead352 of returning an undefined. This fixes problems when passing undefined353 objects to Python semantics expecting APIs.354- traceback support now works properly for PyPy. (Tested with 1.4)355- implemented operator intercepting for sandboxed environments. This356 allows application developers to disable builtin operators for better357 security. (For instance limit the mathematical operators to actual358 integers instead of longs)359- groupby filter now supports dotted notation for grouping by attributes360 of attributes.361- scoped blocks now properly treat toplevel assignments and imports.362 Previously an import suddenly "disappeared" in a scoped block.363- automatically detect newer Python interpreter versions before loading code364 from bytecode caches to prevent segfaults on invalid opcodes. The segfault365 in earlier Jinja2 versions here was not a Jinja2 bug but a limitation in366 the underlying Python interpreter. If you notice Jinja2 segfaulting in367 earlier versions after an upgrade of the Python interpreter you don't have368 to upgrade, it's enough to flush the bytecode cache. This just no longer369 makes this necessary, Jinja2 will automatically detect these cases now.370- the sum filter can now sum up values by attribute. This is a backwards371 incompatible change. The argument to the filter previously was the372 optional starting index which defaults to zero. This now became the373 second argument to the function because it's rarely used.374- like sum, sort now also makes it possible to order items by attribute.375- like sum and sort, join now also is able to join attributes of objects376 as string.377- the internal eval context now has a reference to the environment.378- added a mapping test to see if an object is a dict or an object with379 a similar interface.386- Internal attributes now raise an internal attribute error now387 instead of returning an undefined. This fixes problems when passing388 undefined objects to Python semantics expecting APIs.389- Traceback support now works properly for PyPy. (Tested with 1.4)390- Implemented operator intercepting for sandboxed environments. This391 allows application developers to disable builtin operators for392 better security. (For instance limit the mathematical operators to393 actual integers instead of longs)394- Groupby filter now supports dotted notation for grouping by395 attributes of attributes.396- Scoped blocks now properly treat toplevel assignments and imports.397 Previously an import suddenly "disappeared" in a scoped block.398- Automatically detect newer Python interpreter versions before399 loading code from bytecode caches to prevent segfaults on invalid400 opcodes. The segfault in earlier Jinja2 versions here was not a401 Jinja2 bug but a limitation in the underlying Python interpreter. If402 you notice Jinja2 segfaulting in earlier versions after an upgrade403 of the Python interpreter you don't have to upgrade, it's enough to404 flush the bytecode cache. This just no longer makes this necessary,405 Jinja2 will automatically detect these cases now.406- The sum filter can now sum up values by attribute. This is a407 backwards incompatible change. The argument to the filter previously408 was the optional starting index which defaults to zero. This now409 became the second argument to the function because it's rarely used.410- Like sum, sort now also makes it possible to order items by411 attribute.412- Like sum and sort, join now also is able to join attributes of413 objects as string.414- The internal eval context now has a reference to the environment.415- Added a mapping test to see if an object is a dict or an object with416 a similar interface.417418419Version 2.5.5420-------------421385(re-release of 2.5.4 with built documentation removed for filesize.386 Released on October 18th 2010)422Released 2010-10-18423388- built documentation is no longer part of release.424- Built documentation is no longer part of release.425426427Version 2.5.4428-------------429394(bugfix release, released on October 17th 2010)430Released 2010-10-17431396- Fixed extensions not loading properly with overlays.397- Work around a bug in cpython for the debugger that causes segfaults398 on 64bit big-endian architectures.432- Fixed extensions not loading properly with overlays.433- Work around a bug in cpython for the debugger that causes segfaults434 on 64bit big-endian architectures.435436437Version 2.5.3438-------------439404(bugfix release, released on October 17th 2010)440Released 2010-10-17441406- fixed an operator precedence error introduced in 2.5.2. Statements407 like "-foo.bar" had their implicit parentheses applied around the408 first part of the expression ("(-foo).bar") instead of the more409 correct "-(foo.bar)".442- Fixed an operator precedence error introduced in 2.5.2. Statements443 like "-foo.bar" had their implicit parentheses applied around the444 first part of the expression ("(-foo).bar") instead of the more445 correct "-(foo.bar)".446447448Version 2.5.2449-------------414(bugfix release, released on August 18th 2010)450416- improved setup.py script to better work with assumptions people417 might still have from it (``--with-speedups``).418- fixed a packaging error that excluded the new debug support.451Released 2010-08-18452453- Improved setup.py script to better work with assumptions people454 might still have from it (``--with-speedups``).455- Fixed a packaging error that excluded the new debug support.456457458Version 2.5.1459-------------460424(bugfix release, released on August 17th 2010)461Released 2010-08-17462426- StopIteration exceptions raised by functions called from templates427 are now intercepted and converted to undefineds. This solves a428 lot of debugging grief. (StopIteration is used internally to429 abort template execution)430- improved performance of macro calls slightly.431- babel extraction can now properly extract newstyle gettext calls.432- using the variable ``num`` in newstyle gettext for something else433 than the pluralize count will no longer raise a :exc:`KeyError`.434- removed builtin markup class and switched to markupsafe. For backwards435 compatibility the pure Python implementation still exists but is436 pulled from markupsafe by the Jinja2 developers. The debug support437 went into a separate feature called "debugsupport" and is disabled438 by default because it is only relevant for Python 2.4439- fixed an issue with unary operators having the wrong precedence.463- StopIteration exceptions raised by functions called from templates464 are now intercepted and converted to undefineds. This solves a lot465 of debugging grief. (StopIteration is used internally to abort466 template execution)467- Improved performance of macro calls slightly.468- Babel extraction can now properly extract newstyle gettext calls.469- Using the variable ``num`` in newstyle gettext for something else470 than the pluralize count will no longer raise a :exc:`KeyError`.471- Removed builtin markup class and switched to markupsafe. For472 backwards compatibility the pure Python implementation still exists473 but is pulled from markupsafe by the Jinja2 developers. The debug474 support went into a separate feature called "debugsupport" and is475 disabled by default because it is only relevant for Python 2.4476- Fixed an issue with unary operators having the wrong precedence.477478479Version 2.5480-----------481445(codename Incoherence, released on May 29th 2010)482Released 2010-05-29, codename Incoherence483447- improved the sort filter (should have worked like this for a448 long time) by adding support for case insensitive searches.449- fixed a bug for getattribute constant folding.450- support for newstyle gettext translations which result in a451 nicer in-template user interface and more consistent452 catalogs. (:ref:`newstyle-gettext`)453- it's now possible to register extensions after an environment454 was created.484- Improved the sort filter (should have worked like this for a long485 time) by adding support for case insensitive searches.486- Fixed a bug for getattribute constant folding.487- Support for newstyle gettext translations which result in a nicer488 in-template user interface and more consistent catalogs.489 (:ref:`newstyle-gettext`)490- It's now possible to register extensions after an environment was491 created.492493494Version 2.4.1495-------------496460(bugfix release, released on April 20th 2010)497Released 2010-04-20498462- fixed an error reporting bug for undefineds.499- Fixed an error reporting bug for undefined.500501502Version 2.4503-----------504468(codename Correlation, released on April 13th 2010)505Released 2010-04-13, codename Correlation506470- the environment template loading functions now transparently471 pass through a template object if it was passed to it. This472 makes it possible to import or extend from a template object473 that was passed to the template.474- added a :class:`ModuleLoader` that can load templates from475 precompiled sources. The environment now features a method476 to compile the templates from a configured loader into a zip477 file or folder.478- the _speedups C extension now supports Python 3.479- added support for autoescaping toggling sections and support480 for evaluation contexts (:ref:`eval-context`).481- extensions have a priority now.507- The environment template loading functions now transparently pass508 through a template object if it was passed to it. This makes it509 possible to import or extend from a template object that was passed510 to the template.511- Added a :class:`ModuleLoader` that can load templates from512 precompiled sources. The environment now features a method to513 compile the templates from a configured loader into a zip file or514 folder.515- The _speedups C extension now supports Python 3.516- Added support for autoescaping toggling sections and support for517 evaluation contexts (:ref:`eval-context`).518- Extensions have a priority now.519520521Version 2.3.1522-------------523487(bugfix release, released on February 19th 2010)524Released 2010-02-19525489- fixed an error reporting bug on all python versions490- fixed an error reporting bug on Python 2.4526- Fixed an error reporting bug on all python versions527- Fixed an error reporting bug on Python 2.4528529530Version 2.3531-----------532496(codename 3000 Pythons, released on February 10th 2010)533Released 2010-02-10, codename 3000 Pythons534498- fixes issue with code generator that causes unbound variables499 to be generated if set was used in if-blocks and other small500 identifier problems.501- include tags are now able to select between multiple templates502 and take the first that exists, if a list of templates is503 given.504- fixed a problem with having call blocks in outer scopes that505 have an argument that is also used as local variable in an506 inner frame (#360).507- greatly improved error message reporting (#339)508- implicit tuple expressions can no longer be totally empty.509 This change makes ``{% if %}...{% endif %}`` a syntax error510 now. (#364)511- added support for translator comments if extracted via babel.512- added with-statement extension.513- experimental Python 3 support.535- Fixes issue with code generator that causes unbound variables to be536 generated if set was used in if-blocks and other small identifier537 problems.538- Include tags are now able to select between multiple templates and539 take the first that exists, if a list of templates is given.540- Fixed a problem with having call blocks in outer scopes that have an541 argument that is also used as local variable in an inner frame542 :issue:`360`.543- Greatly improved error message reporting :pr:`339`544- Implicit tuple expressions can no longer be totally empty. This545 change makes ``{% if %}`` a syntax error now. :issue:`364`546- Added support for translator comments if extracted via babel.547- Added with-statement extension.548- Experimental Python 3 support.549550551Version 2.2.1552-------------553519(bugfix release, released on September 14th 2009)554Released 2009-09-14555521- fixes some smaller problems for Jinja2 on Jython.556- Fixes some smaller problems for Jinja2 on Jython.557558559Version 2.2560-----------561527(codename Kong, released on September 13th 2009)562Released 2009-09-13, codename Kong563529- Include statements can now be marked with ``ignore missing`` to skip530 non existing templates.531- Priority of ``not`` raised. It's now possible to write `not foo in bar`532 as an alias to `foo not in bar` like in python. Previously the grammar533 required parentheses (`not (foo in bar)`) which was odd.534- Fixed a bug that caused syntax errors when defining macros or using the535 `{% call %}` tag inside loops.536- Fixed a bug in the parser that made ``{{ foo[1, 2] }}`` impossible.537- Made it possible to refer to names from outer scopes in included templates538 that were unused in the callers frame (#327)539- Fixed a bug that caused internal errors if names where used as iteration540 variable and regular variable *after* the loop if that variable was unused541 *before* the loop. (#331)542- Added support for optional ``scoped`` modifier to blocks.543- Added support for line-comments.544- Added the ``meta`` module.545- Renamed (undocumented) attribute "overlay" to "overlayed" on the546 environment because it was clashing with a method of the same name.547- speedup extension is now disabled by default.564- Include statements can now be marked with ``ignore missing`` to skip565 non existing templates.566- Priority of ``not`` raised. It's now possible to write ``not foo in567 bar`` as an alias to ``foo not in bar`` like in python. Previously568 the grammar required parentheses (``not (foo in bar)``) which was569 odd.570- Fixed a bug that caused syntax errors when defining macros or using571 the ``{% call %}`` tag inside loops.572- Fixed a bug in the parser that made ``{{ foo[1, 2] }}`` impossible.573- Made it possible to refer to names from outer scopes in included574 templates that were unused in the callers frame :issue:`327`575- Fixed a bug that caused internal errors if names where used as576 iteration variable and regular variable *after* the loop if that577 variable was unused *before* the loop. :pr:`331`578- Added support for optional ``scoped`` modifier to blocks.579- Added support for line-comments.580- Added the ``meta`` module.581- Renamed (undocumented) attribute "overlay" to "overlayed" on the582 environment because it was clashing with a method of the same name.583- Speedup extension is now disabled by default.584585586Version 2.1.1587-------------588553(bugfix release, released on December 25th 2008)589Released 2008-12-25590555- Fixed a translation error caused by looping over empty recursive loops.591- Fixed a translation error caused by looping over empty recursive592 loops.593594595Version 2.1596-----------597561(codename Yasuzō, released on November 23rd 2008)598Released 2008-11-23, codename Yasuzō599563- fixed a bug with nested loops and the special loop variable. Before the564 change an inner loop overwrote the loop variable from the outer one after565 iteration.566- fixed a bug with the i18n extension that caused the explicit pluralization567 block to look up the wrong variable.568- fixed a limitation in the lexer that made ``{{ foo.0.0 }}`` impossible.569- index based subscribing of variables with a constant value returns an570 undefined object now instead of raising an index error. This was a bug571 caused by eager optimizing.572- the i18n extension looks up ``foo.ugettext`` now followed by ``foo.gettext``573 if an translations object is installed. This makes dealing with custom574 translations classes easier.575- fixed a confusing behavior with conditional extending. loops were partially576 executed under some conditions even though they were not part of a visible577 area.578- added ``sort`` filter that works like ``dictsort`` but for arbitrary sequences.579- fixed a bug with empty statements in macros.580- implemented a bytecode cache system. (:ref:`bytecode-cache`)581- the template context is now weakref-able582- inclusions and imports "with context" forward all variables now, not only583 the initial context.584- added a cycle helper called ``cycler``.585- added a joining helper called ``joiner``.586- added a ``compile_expression`` method to the environment that allows compiling587 of Jinja expressions into callable Python objects.588- fixed an escaping bug in urlize600- Fixed a bug with nested loops and the special loop variable. Before601 the change an inner loop overwrote the loop variable from the outer602 one after iteration.603- Fixed a bug with the i18n extension that caused the explicit604 pluralization block to look up the wrong variable.605- Fixed a limitation in the lexer that made ``{{ foo.0.0 }}``606 impossible.607- Index based subscribing of variables with a constant value returns608 an undefined object now instead of raising an index error. This was609 a bug caused by eager optimizing.610- The i18n extension looks up ``foo.ugettext`` now followed by611 ``foo.gettext`` if an translations object is installed. This makes612 dealing with custom translations classes easier.613- Fixed a confusing behavior with conditional extending. loops were614 partially executed under some conditions even though they were not615 part of a visible area.616- Added ``sort`` filter that works like ``dictsort`` but for arbitrary617 sequences.618- Fixed a bug with empty statements in macros.619- Implemented a bytecode cache system. (:ref:`bytecode-cache`)620- The template context is now weakref-able621- Inclusions and imports "with context" forward all variables now, not622 only the initial context.623- Added a cycle helper called ``cycler``.624- Added a joining helper called ``joiner``.625- Added a ``compile_expression`` method to the environment that allows626 compiling of Jinja expressions into callable Python objects.627- Fixed an escaping bug in urlize628629630Version 2.0631-----------632594(codename jinjavitus, released on July 17th 2008)633Released 2008-07-17, codename Jinjavitus634596- the subscribing of objects (looking up attributes and items) changed from597 slightly. It's now possible to give attributes or items a higher priority598 by either using dot-notation lookup or the bracket syntax. This also599 changed the AST slightly. ``Subscript`` is gone and was replaced with600 :class:`~jinja2.nodes.Getitem` and :class:`~jinja2.nodes.Getattr`.635- The subscribing of objects (looking up attributes and items) changed636 from slightly. It's now possible to give attributes or items a637 higher priority by either using dot-notation lookup or the bracket638 syntax. This also changed the AST slightly. ``Subscript`` is gone639 and was replaced with :class:`~jinja2.nodes.Getitem` and640 :class:`~jinja2.nodes.Getattr`. For more information see :ref:`the641 implementation details <notes-on-subscriptions>`.642- Added support for preprocessing and token stream filtering for643 extensions. This would allow extensions to allow simplified gettext644 calls in template data and something similar.645- Added :meth:`jinja2.environment.TemplateStream.dump`.646- Added missing support for implicit string literal concatenation.647 ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}``648- ``else`` is optional for conditional expressions. If not given it649 evaluates to ``false``.650- Improved error reporting for undefined values by providing a651 position.652- ``filesizeformat`` filter uses decimal prefixes now per default and653 can be set to binary mode with the second parameter.654- Fixed bug in finalizer655602 For more information see :ref:`the implementation details <notes-on-subscriptions>`.603- added support for preprocessing and token stream filtering for extensions.604 This would allow extensions to allow simplified gettext calls in template605 data and something similar.606- added :meth:`jinja2.environment.TemplateStream.dump`.607- added missing support for implicit string literal concatenation.608 ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}``609- ``else`` is optional for conditional expressions. If not given it evaluates610 to ``false``.611- improved error reporting for undefined values by providing a position.612- ``filesizeformat`` filter uses decimal prefixes now per default and can be613 set to binary mode with the second parameter.614- fixed bug in finalizer656616657Version 2.0rc1658--------------659620(no codename, released on June 9th 2008)660Released 2008-06-09661622- first release of Jinja2662- First release of Jinja2
added:CODE_OF_CONDUCT.md+76 added
1# Contributor Covenant Code of Conduct23## Our Pledge45In the interest of fostering an open and welcoming environment, we as6contributors and maintainers pledge to making participation in our project and7our community a harassment-free experience for everyone, regardless of age, body8size, disability, ethnicity, sex characteristics, gender identity and expression,9level of experience, education, socio-economic status, nationality, personal10appearance, race, religion, or sexual identity and orientation.1112## Our Standards1314Examples of behavior that contributes to creating a positive environment15include:1617* Using welcoming and inclusive language18* Being respectful of differing viewpoints and experiences19* Gracefully accepting constructive criticism20* Focusing on what is best for the community21* Showing empathy towards other community members2223Examples of unacceptable behavior by participants include:2425* The use of sexualized language or imagery and unwelcome sexual attention or26 advances27* Trolling, insulting/derogatory comments, and personal or political attacks28* Public or private harassment29* Publishing others' private information, such as a physical or electronic30 address, without explicit permission31* Other conduct which could reasonably be considered inappropriate in a32 professional setting3334## Our Responsibilities3536Project maintainers are responsible for clarifying the standards of acceptable37behavior and are expected to take appropriate and fair corrective action in38response to any instances of unacceptable behavior.3940Project maintainers have the right and responsibility to remove, edit, or41reject comments, commits, code, wiki edits, issues, and other contributions42that are not aligned to this Code of Conduct, or to ban temporarily or43permanently any contributor for other behaviors that they deem inappropriate,44threatening, offensive, or harmful.4546## Scope4748This Code of Conduct applies both within project spaces and in public spaces49when an individual is representing the project or its community. Examples of50representing a project or community include using an official project e-mail51address, posting via an official social media account, or acting as an appointed52representative at an online or offline event. Representation of a project may be53further defined and clarified by project maintainers.5455## Enforcement5657Instances of abusive, harassing, or otherwise unacceptable behavior may be58reported by contacting the project team at report@palletsprojects.com. All59complaints will be reviewed and investigated and will result in a response that60is deemed necessary and appropriate to the circumstances. The project team is61obligated to maintain confidentiality with regard to the reporter of an incident.62Further details of specific enforcement policies may be posted separately.6364Project maintainers who do not follow or enforce the Code of Conduct in good65faith may face temporary or permanent repercussions as determined by other66members of the project's leadership.6768## Attribution6970This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html7273[homepage]: https://www.contributor-covenant.org7475For answers to common questions about this code of conduct, see76https://www.contributor-covenant.org/faq
deleted:LICENSE-31 removed
1Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.23Some rights reserved.45Redistribution and use in source and binary forms, with or without6modification, are permitted provided that the following conditions are7met:89 * Redistributions of source code must retain the above copyright10 notice, this list of conditions and the following disclaimer.1112 * Redistributions in binary form must reproduce the above13 copyright notice, this list of conditions and the following14 disclaimer in the documentation and/or other materials provided15 with the distribution.1617 * The names of the contributors may not be used to endorse or18 promote products derived from this software without specific19 prior written permission.2021THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR24A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT27LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,28DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY29THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT30(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE31OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:LICENSE.rst+28 added
1Copyright 2007 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
deleted:Makefile-21 removed
1test:2 py.test tests --tb=short34develop:5 pip install --editable .67tox-test:8 @tox910release:11 python scripts/make-release.py1213upload-docs:14 $(MAKE) -C docs html dirhtml latex15 $(MAKE) -C docs/_build/latex all-pdf16 cd docs/_build/; mv html jinja-docs; zip -r jinja-docs.zip jinja-docs; mv jinja-docs html17 scp -r docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/18 scp -r docs/_build/latex/Jinja2.pdf flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/jinja-docs.pdf19 scp -r docs/_build/jinja-docs.zip flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/2021.PHONY: test
modified:MANIFEST.in+1 added-2 removed
1include AUTHORS CHANGES.rst LICENSE2global-exclude *.py[co]1include CHANGES.rst tox.ini2graft artwork3graft docs4prune docs/_build5graft examples
2 unmodified lines
modified:README.rst+50 added-35 removed
1Jinja22~~~~~~1Jinja2=====34Jinja2 is a template engine written in pure Python. It provides a5`Django`_ inspired non-XML syntax but supports inline expressions and6an optional `sandboxed`_ environment.4Jinja is a fast, expressive, extensible templating engine. Special5placeholders in the template allow writing code similar to Python6syntax. Then the template is passed data to render the final document.78Nutshell9--------8It includes:911Here a small example of a Jinja template:10- Template inheritance and inclusion.11- Define and import macros within templates.12- HTML templates can use autoescaping to prevent XSS from untrusted13 user input.14- A sandboxed environment can safely render untrusted templates.15- AsyncIO support for generating templates and calling async16 functions.17- I18N support with Babel.18- Templates are compiled to optimized Python code just-in-time and19 cached, or can be compiled ahead-of-time.20- Exceptions point to the correct line in templates to make debugging21 easier.22- Extensible filters, tests, functions, and even syntax.2324Jinja's philosophy is that while application logic belongs in Python if25possible, it shouldn't make the template designer's job difficult by26restricting functionality too much.272829Installing30----------3132Install and update using `pip`_:3334.. code-block:: text3536 $ pip install -U Jinja23738.. _pip: https://pip.pypa.io/en/stable/quickstart/394041In A Nutshell42-------------4344.. code-block:: jinja4515 {% extends 'base.html' %}16 {% block title %}Memberlist{% endblock %}46 {% extends "base.html" %}47 {% block title %}Members{% endblock %}48 {% block content %}49 <ul>50 {% for user in users %}51 <li><a href="{{ user.url }}">{{ user.username }}</a></li>52 {% endfor %}53 </ul>54 {% endblock %}5525Philosophy26----------5628Application logic is for the controller, but don't make the template designer's29life difficult by restricting functionality too much.57Links58-----5931For more information visit the new `Jinja2 webpage`_ and `documentation`_.3233The `Jinja2 tip`_ is installable via ``pip`` with ``pip install34https://github.com/pallets/jinja/zipball/master``.3536.. _sandboxed: https://en.wikipedia.org/wiki/Sandbox_(computer_security)37.. _Django: https://www.djangoproject.com/38.. _Jinja2 webpage: http://jinja.pocoo.org/39.. _documentation: http://jinja.pocoo.org/docs/40.. _Jinja2 tip: http://jinja.pocoo.org/docs/intro/#as-a-python-egg-via-easy-install4142Builds43------4445+---------------------+------------------------------------------------------------------------------+46| ``master`` | .. image:: https://travis-ci.org/pallets/jinja.svg?branch=master |47| | :target: https://travis-ci.org/pallets/jinja |48+---------------------+------------------------------------------------------------------------------+49| ``2.9-maintenance`` | .. image:: https://travis-ci.org/pallets/jinja.svg?branch=2.9-maintenance |50| | :target: https://travis-ci.org/pallets/jinja |51+---------------------+------------------------------------------------------------------------------+60- Website: https://palletsprojects.com/p/jinja/61- Documentation: https://jinja.palletsprojects.com/62- Releases: https://pypi.org/project/Jinja2/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+16 added-5 removed
1[bdist_wheel]2universal = 131[metadata]5license_file = LICENSE2license_file = LICENSE.rst34[bdist_wheel]5universal = true67[tool:pytest]8minversion = 3.08testpaths = tests910[coverage:run]11branch = True12source =13 jinja214 tests1516[coverage:paths]17source =18 src/jinja219 .tox/*/lib/python*/site-packages/jinja220 .tox/*/site-packages/jinja2
modified:setup.py+45 added-73 removed
1# -*- coding: utf-8 -*-2"""3Jinja24~~~~~~1import io2import re36Jinja2 is a template engine written in pure Python. It provides a7`Django`_ inspired non-XML syntax but supports inline expressions and8an optional `sandboxed`_ environment.910Nutshell11--------1213Here a small example of a Jinja template::1415 {% extends 'base.html' %}16 {% block title %}Memberlist{% endblock %}17 {% block content %}18 <ul>19 {% for user in users %}20 <li><a href="{{ user.url }}">{{ user.username }}</a></li>21 {% endfor %}22 </ul>23 {% endblock %}2425Philosophy26----------2728Application logic is for the controller but don't try to make the life29for the template designer too hard by giving him too few functionality.3031For more information visit the new `Jinja2 webpage`_ and `documentation`_.3233.. _sandboxed: https://en.wikipedia.org/wiki/Sandbox_(computer_security)34.. _Django: https://www.djangoproject.com/35.. _Jinja2 webpage: http://jinja.pocoo.org/36.. _documentation: http://jinja.pocoo.org/2/documentation/37"""4from setuptools import find_packages5from setuptools import setup67with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()910with io.open("jinja2/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)1213setup(42 name='Jinja2',43 version='2.11.dev',44 url='http://jinja.pocoo.org/',45 license='BSD',46 author='Armin Ronacher',47 author_email='armin.ronacher@active-4.com',48 description='A small but fast and easy to use stand-alone template '49 'engine written in pure python.',50 long_description=__doc__,51 # jinja is egg safe. But we hate eggs52 zip_safe=False,14 name="Jinja2",15 version=version,16 url="https://palletsprojects.com/p/jinja/",17 project_urls={18 "Documentation": "https://jinja.palletsprojects.com/",19 "Code": "https://github.com/pallets/jinja",20 "Issue tracker": "https://github.com/pallets/jinja/issues",21 },22 license="BSD-3-Clause",23 author="Armin Ronacher",24 author_email="armin.ronacher@active-4.com",25 maintainer="Pallets",26 maintainer_email="contact@palletsprojects.com",27 description="A very fast and expressive template engine.",28 long_description=readme,29 classifiers=[54 'Development Status :: 5 - Production/Stable',55 'Environment :: Web Environment',56 'Intended Audience :: Developers',57 'License :: OSI Approved :: BSD License',58 'Operating System :: OS Independent',59 'Programming Language :: Python',60 'Programming Language :: Python :: 2',61 'Programming Language :: Python :: 2.7',62 'Programming Language :: Python :: 3',63 'Programming Language :: Python :: 3.4',64 'Programming Language :: Python :: 3.5',65 'Programming Language :: Python :: 3.6',66 'Programming Language :: Python :: 3.7',67 'Programming Language :: Python :: Implementation :: CPython',68 'Programming Language :: Python :: Implementation :: PyPy',69 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',70 'Topic :: Software Development :: Libraries :: Python Modules',71 'Topic :: Text Processing :: Markup :: HTML'30 "Development Status :: 5 - Production/Stable",31 "Environment :: Web Environment",32 "Intended Audience :: Developers",33 "License :: OSI Approved :: BSD License",34 "Operating System :: OS Independent",35 "Programming Language :: Python",36 "Programming Language :: Python :: 2",37 "Programming Language :: Python :: 2.7",38 "Programming Language :: Python :: 3",39 "Programming Language :: Python :: 3.5",40 "Programming Language :: Python :: 3.6",41 "Programming Language :: Python :: 3.7",42 "Programming Language :: Python :: Implementation :: CPython",43 "Programming Language :: Python :: Implementation :: PyPy",44 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",45 "Topic :: Software Development :: Libraries :: Python Modules",46 "Topic :: Text Processing :: Markup :: HTML",47 ],73 packages=['jinja2'],74 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",75 install_requires=['MarkupSafe>=0.23'],76 extras_require={'i18n': ['Babel>=0.8']},48 packages=find_packages(),49 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",50 include_package_data=True,78 entry_points="""79 [babel.extractors]80 jinja2 = jinja2.ext:babel_extract[i18n]81 """51 install_requires=["MarkupSafe>=0.23"],52 extras_require={"i18n": ["Babel>=0.8"]},53 entry_points={"babel.extractors": ["jinja2 = jinja2.ext:babel_extract[i18n]"]},54)
modified:tox.ini+17 added-20 removed
1[tox]2envlist =3 py{37,36,35,34,27,py3,py}3 py{37,36,35,27,py3,py}4 docs-html5 coverage-report5 coverage6skip_missing_interpreters = true78[testenv]8passenv = LANG9usedevelop = true9deps =11 pytest>=3,<3.710 coverage11 pytest12commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}1314commands = coverage run -p -m pytest {posargs}1514[testenv:docs-html]17deps = sphinx18commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html15deps =16 Sphinx17 Pallets-Sphinx-Themes18 sphinxcontrib-log-cabinet19 sphinx-issues20commands = sphinx-build -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html2120[testenv:docs-linkcheck]21deps = sphinx22commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck2324[testenv:coverage-report]22[testenv:coverage]23deps = coverage24skip_install = true25commands =26 coverage combine29 coverage report27 coverage html28 coverage report2932[testenv:codecov]33passenv = CI TRAVIS TRAVIS_*34deps = codecov30[testenv:coverage-ci]31deps = coverage32skip_install = true33commands =34 coverage combine38 coverage report39 codecov35 # Ignoring errors because 2.7.15 and 3.5.5 on Azure can't parse async files.36 coverage xml --ignore-errors