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
Provenance
- Commit
7cf0e6d- Tree
6279963- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7d00a40- Parent 2
381d72a
69 files changed+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
1234567891011121314151617181920<h3>About Jinja2</h3><p> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.</p><h3>Other Formats</h3><p> You can download the documentation in other formats as well:</p><ul> <li><a href="http://jinja.pocoo.org/docs/jinja-docs.pdf">as PDF</a> <li><a href="http://jinja.pocoo.org/docs/jinja-docs.zip">as zipped HTML</a></ul><h3>Useful Links</h3><ul> <li><a href="http://jinja.pocoo.org/">The Jinja2 Website</a></li> <li><a href="https://pypi.org/project/Jinja2/">Jinja2 @ PyPI</a></li> <li><a href="https://github.com/pallets/jinja">Jinja2 @ github</a></li></ul>deleted:docs/_templates/sidebarlogo.html-3 removed
123<p class="logo"><a href="{{ pathto(master_doc) }}"> <img class="logo" src="{{ pathto('_static/jinja-small.png', 1) }}" alt="Logo"/></a></p>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- */8-9-@import url(http://fonts.googleapis.com/css?family=Crimson+Text);10-11-{% set page_width = '940px' %}12-{% set sidebar_width = '220px' %}13-{% set font_family = 'Georgia, serif' %}14-{% set header_font_family = 'Crimson Text, ' ~ font_family %}15-16-@import url("basic.css");17-18-/* -- page layout ----------------------------------------------------------- */19-20-body {21- font-family: {{ font_family }};22- font-size: 17px;23- background-color: white;24- color: #000;25- margin: 0;26- padding: 0;27-}28-29-div.document {30- width: {{ page_width }};31- margin: 30px auto 0 auto;32-}33-34-div.documentwrapper {35- float: left;36- width: 100%;37-}38-39-div.bodywrapper {40- margin: 0 0 0 {{ sidebar_width }};41-}42-43-div.sphinxsidebar {44- width: {{ sidebar_width }};45-}46-47-hr {48- border: 1px solid #B1B4B6;49-}50-51-div.body {52- background-color: #ffffff;53- color: #3E4349;54- padding: 0 30px 0 30px;55-}56-57-img.floatingflask {58- padding: 0 0 10px 10px;59- float: right;60-}61-62-div.footer {63- width: {{ page_width }};64- margin: 20px auto 30px auto;65- font-size: 14px;66- color: #888;67- text-align: right;68-}69-70-div.footer a {71- color: #888;72-}73-74-div.related {75- display: none;76-}77-78-div.sphinxsidebar a {79- color: #444;80- text-decoration: none;81- border-bottom: 1px dotted #999;82-}83-84-div.sphinxsidebar a:hover {85- border-bottom: 1px solid #999;86-}87-88-div.sphinxsidebar {89- font-size: 15px;90- line-height: 1.5;91-}92-93-div.sphinxsidebarwrapper {94- padding: 18px 10px;95-}96-97-div.sphinxsidebarwrapper p.logo {98- padding: 0 0 20px 0;99- margin: 0;100- text-align: center;101-}102-103-div.sphinxsidebar h3,104-div.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-}112-113-div.sphinxsidebar h4 {114- font-size: 20px;115-}116-117-div.sphinxsidebar h3 a {118- color: #444;119-}120-121-div.sphinxsidebar p.logo a,122-div.sphinxsidebar h3 a,123-div.sphinxsidebar p.logo a:hover,124-div.sphinxsidebar h3 a:hover {125- border: none;126-}127-128-div.sphinxsidebar p {129- color: #555;130- margin: 10px 0;131-}132-133-div.sphinxsidebar ul {134- margin: 10px 0;135- padding: 0;136- color: #000;137-}138-139-div.sphinxsidebar input {140- border: 1px solid #ccc;141- font-family: {{ font_family }};142- font-size: 14px;143-}144-145-div.sphinxsidebar form.search input[name="q"] {146- width: 130px;147-}148-149-/* -- body styles ----------------------------------------------------------- */150-151-a {152- color: #aa0000;153- text-decoration: underline;154-}155-156-a:hover {157- color: #dd0000;158- text-decoration: underline;159-}160-161-div.body h1,162-div.body h2,163-div.body h3,164-div.body h4,165-div.body h5,166-div.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-}173-174-div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }175-div.body h2 { font-size: 180%; }176-div.body h3 { font-size: 150%; }177-div.body h4 { font-size: 130%; }178-div.body h5 { font-size: 100%; }179-div.body h6 { font-size: 100%; }180-181-a.headerlink {182- color: #ddd;183- padding: 0 4px;184- text-decoration: none;185-}186-187-a.headerlink:hover {188- color: #444;189- background: #eaeaea;190-}191-192-div.body p, div.body dd, div.body li {193- line-height: 1.4em;194-}195-196-div.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-}203-204-div.admonition tt.xref, div.admonition a tt {205- border-bottom: 1px solid #fafafa;206-}207-208-dd div.admonition {209- margin-left: -60px;210- padding-left: 60px;211-}212-213-div.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-}221-222-div.admonition p.last {223- margin-bottom: 0;224-}225-226-div.highlight {227- background-color: white;228-}229-230-dt:target, .highlight {231- background: #FAF3E8;232-}233-234-div.note {235- background-color: #eee;236- border: 1px solid #ccc;237-}238-239-div.seealso {240- background-color: #ffc;241- border: 1px solid #ff6;242-}243-244-div.topic {245- background-color: #eee;246-}247-248-p.admonition-title {249- display: inline;250-}251-252-p.admonition-title:after {253- content: ":";254-}255-256-pre, tt {257- font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;258- font-size: 0.85em;259-}260-261-img.screenshot {262-}263-264-tt.descname, tt.descclassname {265- font-size: 0.95em;266-}267-268-tt.descname {269- padding-right: 0.08em;270-}271-272-img.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-}277-278-table.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-}284-285-table.docutils td, table.docutils th {286- border: 1px solid #888;287- padding: 0.25em 0.7em;288-}289-290-table.field-list, table.footnote {291- border: none;292- -moz-box-shadow: none;293- -webkit-box-shadow: none;294- box-shadow: none;295-}296-297-table.footnote {298- margin: 15px 0;299- width: 100%;300- border: 1px solid #eee;301- background: #fdfdfd;302- font-size: 0.9em;303-}304-305-table.footnote + table.footnote {306- margin-top: -15px;307- border-top: none;308-}309-310-table.field-list th {311- padding: 0 0.8em 0 0;312-}313-314-table.field-list td {315- padding: 0;316-}317-318-table.footnote td.label {319- width: 0px;320- padding: 0.3em 0 0.3em 0.5em;321-}322-323-table.footnote td {324- padding: 0.3em 0.5em;325-}326-327-dl {328- margin: 0;329- padding: 0;330-}331-332-dl dd {333- margin-left: 30px;334-}335-336-blockquote {337- margin: 0 0 0 30px;338- padding: 0;339-}340-341-ul, ol {342- margin: 10px 0 10px 30px;343- padding: 0;344-}345-346-pre {347- background: #eee;348- padding: 7px 30px;349- margin: 15px -30px;350- line-height: 1.3em;351-}352-353-dl pre, blockquote pre, li pre {354- margin-left: -60px;355- padding-left: 60px;356-}357-358-dl dl pre {359- margin-left: -90px;360- padding-left: 90px;361-}362-363-tt {364- background-color: #E8EFF0;365- color: #222;366- /* padding: 1px 2px; */367-}368-369-tt.xref, a tt {370- background-color: #E8EFF0;371- border-bottom: 1px solid white;372-}373-374-a.reference {375- text-decoration: none;376- border-bottom: 1px dotted #bb0000;377-}378-379-a.reference:hover {380- border-bottom: 1px solid #dd0000;381-}382-383-a.footnote-reference {384- text-decoration: none;385- font-size: 0.7em;386- vertical-align: top;387- border-bottom: 1px dotted #bb0000;388-}389-390-a.footnote-reference:hover {391- border-bottom: 1px solid #dd0000;392-}393-394-a:hover tt {395- background: #EEE;396-}deleted:docs/_themes/jinja/layout.html-8 removed
12345678{%- extends "basic/layout.html" %}{%- block relbar2 %}{% endblock %}{%- block footer %} <div class="footer"> © Copyright {{ copyright }}. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>. </div>{%- endblock %}deleted:docs/_themes/jinja/relations.html-19 removed
12345678910111213141516171819<h3>Related Topics</h3><ul> <li><a href="{{ pathto(master_doc) }}">Documentation overview</a><ul> {%- for parent in parents %} <li><a href="{{ parent.link|e }}">{{ parent.title }}</a><ul> {%- endfor %} {%- if prev %} <li>Previous: <a href="{{ prev.link|e }}" title="{{ _('previous chapter') }}">{{ prev.title }}</a></li> {%- endif %} {%- if next %} <li>Next: <a href="{{ next.link|e }}" title="{{ _('next chapter') }}">{{ next.title }}</a></li> {%- endif %} {%- for parent in parents %} </ul></li> {%- endfor %} </ul></li></ul>deleted:docs/_themes/jinja/theme.conf-3 removed
1-[theme]2-inherit = basic3-stylesheet = jinja.cssdeleted:docs/_themes/LICENSE-37 removed
1-Copyright (c) 2010 by Armin Ronacher.2-3-Some rights reserved.4-5-Redistribution and use in source and binary forms of the theme, with or6-without modification, are permitted provided that the following conditions7-are met:8-9-* Redistributions of source code must retain the above copyright10- notice, this list of conditions and the following disclaimer.11-12-* 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.16-17-* The names of the contributors may not be used to endorse or18- promote products derived from this software without specific19- prior written permission.20-21-We kindly ask you to only use these themes in an unmodified manner just22-for Flask and Flask-related products, not for unrelated projects. If you23-like the visual style and want to use it for your own projects, please24-consider making some larger changes to the themes (such as changing25-font faces, sizes, colors or margins).26-27-THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"28-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE29-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE30-ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE31-LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR32-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF33-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS34-INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN35-CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)36-ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE37-POSSIBILITY OF SUCH DAMAGE.deleted:docs/_themes/README-31 removed
1-Flask Sphinx Styles2-===================3-4-This repository contains sphinx styles for Flask and Flask related5-projects. To use this style in your Sphinx documentation, follow6-this guide:7-8-1. put this folder as _themes into your docs folder. Alternatively9- you can also use git submodules to check out the contents there.10-2. add this to your conf.py:11-12- sys.path.append(os.path.abspath('_themes'))13- html_theme_path = ['_themes']14- html_theme = 'flask'15-16-The following themes exist:17-18-- '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.22-23-The following options exist for the flask_small theme:24-25- [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" badgemodified:docs/api.rst+7 added-4 removed
1 API2 ===3 4 .. module:: jinja25+ :noindex:6 :synopsis: public Jinja2 API7 8 This document describes the API to Jinja2 and not the template language. It9 will be most useful as reference to those implementing the template interface36 unmodified lines46 template = env.get_template('mytemplate.html')47 48 To render it with some variables, just call the :meth:`render` method::49 49- print template.render(the='variables', go='here')50+ print(template.render(the='variables', go='here'))51 52 Using a template loader rather than passing strings to :class:`Template`53 or :meth:`Environment.from_string` has multiple advantages. Besides being54 a lot easier to use it also enables template inheritance.59 unmodified lines114 >>> m.b115 u'f\xf6\xf6'116 117 117-.. _Unicode documentation: https://docs.python.org/dev/howto/unicode.html118+.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html119 120 High Level API121 --------------122 199 unmodified lines322 unable to look up a name or access an attribute one of those objects is323 created and returned. Some operations on undefined values are then allowed,324 others fail.325 325-The closest to regular Python behavior is the `StrictUndefined` which326+The closest to regular Python behavior is the :class:`StrictUndefined` which327 disallows all operations beside testing if it's an undefined object.328 329 .. autoclass:: jinja2.Undefined()330 22 unmodified lines353 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.356 357+.. autoclass:: jinja2.ChainableUndefined()358+359 .. autoclass:: jinja2.DebugUndefined()360 361 .. autoclass:: jinja2.StrictUndefined()362 473 unmodified lines836 837 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 linesmodified:docs/cache_extension.py+1 added-1 removed
2 unmodified lines3 4 5 class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.7- tags = set(['cache'])7+ tags = {'cache'}8 9 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)11 45 unmodified linesmodified:docs/changelog.rst+2 added-1 removed
1-.. module:: jinja21+Changelog2+=========3 4 .. include:: ../CHANGES.rstmodified: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.1+from pallets_sphinx_themes import get_version2+from pallets_sphinx_themes import ProjectLink3 14-import sys, os4+# Project --------------------------------------------------------------5 16-# 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.19-sys.path.append(os.path.dirname(os.path.abspath(__file__)))6+project = "Jinja"7+copyright = "2007 Pallets"8+author = "Pallets"9+release, version = get_version("Jinja2")10 21-# General configuration22-# ---------------------11+# General --------------------------------------------------------------12 24-# Add any Sphinx extension module names here, as strings. They can be extensions25-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.26-extensions = ['sphinx.ext.autodoc', 'jinjaext']27-28-# Add any paths that contain templates here, relative to this directory.29-templates_path = ['_templates']30-31-# The suffix of source filenames.32-source_suffix = '.rst'33-34-# The master toctree document.35-master_doc = 'index'36-37-# General substitutions.38-project = 'Jinja2'39-copyright = '2008, Armin Ronacher'40-41-# The default replacements for |version| and |release|, also used in various42-# other places throughout the built documents.43-#44-# The short X.Y version.45-import pkg_resources46-try:47- release = pkg_resources.get_distribution('Jinja2').version48-except 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)54-if 'dev' in release:55- release = release.split('dev')[0] + 'dev'56-version = '.'.join(release.split('.')[:2])57-58-# 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.62-today_fmt = '%B %d, %Y'63-64-# List of documents that shouldn't be included in the build.65-#unused_docs = []66-67-# If true, '()' will be appended to :func: etc. cross-reference text.68-#add_function_parentheses = True69-70-# If true, the current module name will be prepended to all description71-# unit titles (such as .. function::).72-#add_module_names = True73-74-# If true, sectionauthor and moduleauthor directives will be shown in the75-# output. They are ignored by default.76-#show_authors = False77-78-# The name of the Pygments (syntax highlighting) style to use.79-pygments_style = 'jinjaext.JinjaStyle'80-81-82-# Options for HTML output83-# -----------------------84-85-html_theme = 'jinja'86-html_theme_path = ['_themes']87-88-# The name for this set of Sphinx documents. If None, it defaults to89-# "<project> v<release> documentation".90-#html_title = None91-92-# 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".95-html_static_path = ['_static']96-97-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,98-# using the given strftime format.99-html_last_updated_fmt = '%b %d, %Y'100-101-# If true, SmartyPants will be used to convert quotes and dashes to102-# typographically correct entities.103-#html_use_smartypants = True104-105-# no modindex106-html_use_modindex = False107-108-# If true, the reST sources are included in the HTML build as _sources/<name>.109-#html_copy_source = True110-111-# If true, an OpenSearch description file will be output, and all pages will112-# contain a <link> tag referring to it.113-#html_use_opensearch = False114-115-# Output file base name for HTML help builder.116-htmlhelp_basename = 'Jinja2doc'117-118-119-# Options for LaTeX output120-# ------------------------121-122-# The paper size ('letter' or 'a4').123-latex_paper_size = 'a4'124-125-# The font size ('10pt', '11pt' or '12pt').126-#latex_font_size = '10pt'127-128-# Grouping the document tree into LaTeX files. List of tuples129-# (source start file, target name, title, author, document class [howto/manual]).130-latex_documents = [131- ('latexindex', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher',132- 'manual'),13+master_doc = "index"14+extensions = [15+ "sphinx.ext.autodoc",16+ "sphinx.ext.intersphinx",17+ "pallets_sphinx_themes",18+ "sphinxcontrib.log_cabinet",19+ "sphinx_issues",20 ]21+intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}22+issues_github_path = "pallets/jinja"23 135-# Additional stuff for LaTeX136-latex_elements = {137- 'fontpkg': r'\usepackage{mathpazo}',138- 'papersize': 'a4paper',139- 'pointsize': '12pt',140- 'preamble': r'''141-\usepackage{jinjastyle}24+# HTML -----------------------------------------------------------------25 143-% i hate you latex144-\DeclareUnicodeCharacter{14D}{o}145-'''26+html_theme = "jinja"27+html_theme_options = {"index_sidebar_logo": False}28+html_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 }147-148-latex_use_parts = True149-150-latex_additional_files = ['jinjastyle.sty', 'logo.pdf']151-152-# If false, no module index is generated.153-latex_use_modindex = False154-37 html_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 }41+singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}42+html_static_path = ["_static"]43+html_favicon = "_static/jinja-logo-sidebar.png"44+html_logo = "_static/jinja-logo-sidebar.png"45+html_title = "Jinja Documentation ({})".format(version)46+html_show_sourcelink = False47+48+# LaTeX ----------------------------------------------------------------49+50+latex_documents = [51+ (master_doc, "Jinja-{}.tex".format(version), html_title, author, "manual")52+]deleted:docs/contents.rst.inc-24 removed
1-Jinja2 Documentation2---------------------3-4-.. toctree::5- :maxdepth: 26-7- intro8- api9- sandbox10- nativetypes11- templates12- extensions13- integration14- switching15- tricks16-17-Additional Information18-----------------------19-20-.. toctree::21- :maxdepth: 222-23- faq24- changelogmodified:docs/extensions.rst+47 added-35 removed
12 unmodified lines13 14 Extensions are added to the Jinja2 environment at creation time. Once the15 environment is created additional extensions cannot be added. To add an16 extension pass a list of extension classes or import paths to the17-`extensions` parameter of the :class:`Environment` constructor. The following17+``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following18 example creates a Jinja2 environment with the i18n extension loaded::19 20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])21 2 unmodified lines24 25 i18n Extension26 --------------27 28-**Import name:** `jinja2.ext.i18n`28+**Import name:** ``jinja2.ext.i18n``29 30 The i18n extension can be used in combination with `gettext`_ or `babel`_. If31-the i18n extension is enabled Jinja2 provides a `trans` statement that marks32-the wrapped string as translatable and calls `gettext`.31+the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32+the wrapped string as translatable and calls ``gettext``.33 34-After enabling, dummy `_` function that forwards calls to `gettext` is added34+After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35 to the environment globals. An internationalized application then has to36-provide a `gettext` function and optionally an `ngettext` function into the36+provide a ``gettext`` function and optionally an ``ngettext`` function into the37 namespace, either globally or for each rendering.38 39 Environment Methods40 ~~~~~~~~~~~~~~~~~~~3 unmodified lines44 45 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)46 47 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.51 52 .. versionchanged:: 2.5 newstyle gettext added53 54 .. method:: jinja2.Environment.install_null_translations(newstyle=False)5 unmodified lines60 .. versionchanged:: 2.5 newstyle gettext added61 62 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)63 64- 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.68 69- 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.71 72 .. versionadded:: 2.573 7 unmodified lines81 82 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:84 85- * `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).90 91 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92 can be used to extract strings for babel.93 5 unmodified lines99 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])101 env.install_gettext_translations(translations)102 103-The `get_gettext_translations` function would return the translator for the104-current configuration. (For example by using `gettext.find`)103+The ``get_gettext_translations`` function would return the translator for the104+current configuration. (For example by using ``gettext.find``)105 106-The usage of the `i18n` extension for template designers is covered as part106+The usage of the ``i18n`` extension for template designers is covered as part107 :ref:`of the template documentation <i18n-in-templates>`.108 109-.. _gettext: https://docs.python.org/dev/library/gettext109+.. _gettext: https://docs.python.org/3/library/gettext.html110 .. _Babel: http://babel.pocoo.org/111 112 .. _newstyle-gettext:113 53 unmodified lines167 168 Expression Statement169 --------------------170 171-**Import name:** `jinja2.ext.do`171+**Import name:** ``jinja2.ext.do``172 173-The "do" aka expression-statement extension adds a simple `do` tag to the173+The "do" aka expression-statement extension adds a simple ``do`` tag to the174 template engine that works like a variable expression but ignores the175 return value.176 177 .. _loopcontrols-extension:178 179 Loop Controls180 -------------181 182-**Import name:** `jinja2.ext.loopcontrols`182+**Import name:** ``jinja2.ext.loopcontrols``183 184-This extension adds support for `break` and `continue` in loops. After184+This extension adds support for ``break`` and ``continue`` in loops. After185 enabling, Jinja2 provides those two keywords which work exactly like in186 Python.187 188 .. _with-extension:189 190 With Statement191 --------------192 193-**Import name:** `jinja2.ext.with_`193+**Import name:** ``jinja2.ext.with_``194 195 .. versionchanged:: 2.9196 197-This extension is now built-in and no longer does anything.197+ This extension is now built-in and no longer does anything.198 199 .. _autoescape-extension:200 201 Autoescape Extension202 --------------------203 204-**Import name:** `jinja2.ext.autoescape`204+**Import name:** ``jinja2.ext.autoescape``205 206 .. versionchanged:: 2.9207 208-This extension was removed and is now built-in. Enabling the extension209-no longer does anything.208+ This extension was removed and is now built-in. Enabling the209+ extension no longer does anything.210 211 212+.. _debug-extension:213+214+Debug Extension215+---------------216+217+**Import name:** ``jinja2.ext.debug``218+219+Adds a ``{% debug %}`` tag to dump the current context as well as the220+available filters and tests. This is useful to see what's available to221+use in the template without setting up a debugger.222+223+224 .. _writing-extensions:225 226 Writing Extensions227 ------------------14 unmodified lines242 243 Example Extension244 ~~~~~~~~~~~~~~~~~245 234-The following example implements a `cache` tag for Jinja2 by using the235-`Werkzeug`_ caching contrib module:246+The following example implements a ``cache`` tag for Jinja2 by using the247+`cachelib`_ library:248 249 .. literalinclude:: cache_extension.py250 :language: python251 252 And here is how you use it in an environment::253 254 from jinja2 import Environment243- from werkzeug.contrib.cache import SimpleCache255+ from cachelib import SimpleCache256 257 env = Environment(extensions=[FragmentCacheExtension])258 env.fragment_cache = SimpleCache()259 7 unmodified lines267 ...268 </div>269 {% endcache %}270 259-.. _Werkzeug: http://werkzeug.pocoo.org/271+.. _cachelib: https://github.com/pallets/cachelib272 273 Extension API274 ~~~~~~~~~~~~~275 27 unmodified lines303 304 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``.308 309 .. attribute:: name310 311 The load name of the template.18 unmodified lines330 331 .. attribute:: type332 333 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.335 336 .. attribute:: value337 338 The value of the token.17 unmodified lines356 For more information have a look at the repr of :meth:`jinja2.Environment.parse`.357 358 .. module:: jinja2.nodes359 348-.. jinjanodes::360+.. jinja:nodes:: jinja2.nodes.Node361 362 .. autoexception:: Impossiblemodified:docs/faq.rst+3 added-3 removed
24 unmodified lines25 speaking the performance of a template engine doesn't matter much as the26 usual bottleneck in a web application is either the database or the application27 code.28 29-.. _Mako: http://www.makotemplates.org/29+.. _Mako: https://www.makotemplates.org/30 31 How Compatible is Jinja2 with Django?32 -------------------------------------33 118 unmodified lines152 153 Python 2.3 is missing a lot of features that are used heavily in Jinja2. This154 decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155 harder to maintain the code for older Python versions. If you really need156-Python 2.3 support you either have to use `Jinja 1`_ or other templating156+Python 2.3 support you either have to use Jinja 1 or other templating157 engines that still support 2.3.158 159 Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160 Python 2 and 3 by the same sourcecode (without using 2to3). It was required to30 unmodified lines191 templates passing information to the parent template. To avoid this192 issue rename the macro or variable in the parent template to have an193 uncommon prefix.194 195-.. _Jinja 1: http://jinja.pocoo.org/1/195+.. _Jinja 1: https://pypi.org/project/Jinja/modified:docs/index.rst+24 added-7 removed
1-Welcome to Jinja22-=================1+.. rst-class:: hide-header2 3+Jinja4+=====5+6+.. image:: _static/jinja-logo.png7+ :align: center8+ :target: https://palletsprojects.com/p/jinja/9+4-Jinja2 is a modern and designer-friendly templating language for Python,10+Jinja is a modern and designer-friendly templating language for Python,11 modelled after Django's templates. It is fast, widely used and secure12 with the optional sandboxed template execution environment:13 14 .. sourcecode:: html+jinja4 unmodified lines19 <li><a href="{{ user.url }}">{{ user.username }}</a></li>20 {% endfor %}21 </ul>22 17-**Features:**23+Features:24 25 - sandboxed execution26 - powerful automatic HTML escaping system for XSS prevention27 - template inheritance2 unmodified lines30 - easy to debug. Line numbers of exceptions directly point to31 the correct line in the template.32 - configurable syntax33 28-.. include:: contents.rst.inc34+.. toctree::35+ :maxdepth: 236+ :caption: Contents:37 30-If you can't find the information you're looking for, have a look at the31-index or try to find it using the search function:38+ intro39+ api40+ sandbox41+ nativetypes42+ templates43+ extensions44+ integration45+ switching46+ tricks47+ faq48+ changelog49 50 * :ref:`genindex`51 * :ref:`search`modified:docs/integration.rst+2 added-2 removed
74 unmodified lines75 snippet and add it into your `config/environment.py`::76 77 config['pylons.strict_c'] = True78 79-.. _Pylons: http://www.pylonshq.com/79+.. _Pylons: https://pylonshq.com/80 81 TextMate82 --------83 17 unmodified lines101 <https://github.com/mitsuhiko/vim-jinja>`_ repository for installing in the102 ``bundle/`` directory.103 104 .. _Babel: http://babel.pocoo.org/105-.. _Vim: http://www.vim.org/105+.. _Vim: https://www.vim.org/106 .. _Pathogen: https://github.com/tpope/vim-pathogenmodified:docs/intro.rst+3 added-3 removed
40 unmodified lines41 which will install the package via `distribute` in development mode. This also42 has the advantage that the C extensions are compiled.43 44 .. _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/48 49 50 MarkupSafe Dependency51 ~~~~~~~~~~~~~~~~~~~~~52 53 As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you install54 Jinja2 via ``pip`` it will be installed automatically for you.55 56-.. _MarkupSafe: https://pypi.org/project/MarkupSafe/56+.. _MarkupSafe: https://markupsafe.palletsprojects.com/57 58 Basic API Usage59 ---------------60 22 unmodified linesdeleted:docs/jinjaext.py-206 removed
1-# -*- coding: utf-8 -*-2-"""3- Jinja Documentation Extensions4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Support for automatically documenting filters and tests.7-8- :copyright: Copyright 2008 by Armin Ronacher.9- :license: BSD.10-"""11-import os12-import re13-import inspect14-15-import logging16-17-import jinja218-from itertools import islice19-from types import BuiltinFunctionType20-from docutils import nodes21-from docutils.statemachine import ViewList22-from sphinx.ext.autodoc import prepare_docstring23-from sphinx.application import TemplateBridge24-from pygments.style import Style25-from pygments.token import Keyword, Name, Comment, String, Error, \26- Number, Operator, Generic27-from jinja2 import Environment, FileSystemLoader28-from jinja2._compat import abc29-30-31-def 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.children42-43-44-class 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',51-52- Keyword: 'bold #B80000',53- Keyword.Type: '#808080',54-55- Operator.Word: 'bold #B80000',56-57- 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',65-66- String: '#AA891C',67- Number: '#444444',68-69- 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',79-80- Error: '#F00 bg:#FAA'81- }82-83-84-_sig_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\(.*?\))')85-86-87-def 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 result111-112-113-def dump_functions(mapping):114- def directive(115- dirname, arguments, options, content, lineno, content_offset,116- block_text, state, state_machine117- ):118- reverse_mapping = {}119-120- for name, func in mapping.items():121- reverse_mapping.setdefault(func, []).append(name)122-123- filters = []124- compare_ops = set(('lt', 'le', 'eq', 'ne', 'ge', 'gt'))125-126- 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))131-132- filters.sort()133- result = ViewList()134-135- for name, aliases, func in filters:136- for item in format_function(name, aliases, func):137- result.append(item, '<jinjaext>')138-139- node = nodes.paragraph()140- state.nested_parse(result, content_offset, node)141- return node.children142-143- return directive144-145-146-from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS147-jinja_filters = dump_functions(DEFAULT_FILTERS)148-jinja_tests = dump_functions(DEFAULT_TESTS)149-150-151-def 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)179-180-181-def 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)199-200-201-def 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}4-5-\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-}42-43-\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-}52-53-\fancypagestyle{plain}{54- \fancyhf{}55- \fancyfoot[LE,RO]{{\thepage}}56- \renewcommand{\headrulewidth}{0pt}57- \renewcommand{\footrulewidth}{0.4pt}58-}59-60-\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}68-69-\ChNameVar{\raggedleft\normalsize}70-\ChNumVar{\raggedleft \bfseries\Large}71-\ChTitleVar{\raggedleft \rm\Huge}72-73-\renewcommand\thepart{\@Roman\c@part}74-\renewcommand\part{%75- \pagestyle{plain}76- \if@noskipsec \leavevmode \fi77- \cleardoublepage78- \vspace*{6cm}%79- \@afterindentfalse80- \secdef\@part\@spart}81-82-\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}109-110-% use inconsolata font111-\usepackage{inconsolata}112-113-% fix single quotes, for inconsolata. (does not work)114-%%\usepackage{textcomp}115-%%\begingroup116-%% \catcode`'=\active117-%% \g@addto@macro\@noligs{\let'\textsinglequote}118-%% \endgroup119-%%\endinputdeleted:docs/latexindex.rst-6 removed
1-:orphan:2-3-Jinja2 Documentation4-====================5-6-.. include:: contents.rst.incdeleted:docs/logo.pdfbinary
A binary file, deleted.
added:docs/make.bat+35 added
1+@ECHO OFF2+3+pushd %~dp04+5+REM Command file for Sphinx documentation6+7+if "%SPHINXBUILD%" == "" (8+ set SPHINXBUILD=sphinx-build9+)10+set SOURCEDIR=.11+set BUILDDIR=_build12+13+if "%1" == "" goto help14+15+%SPHINXBUILD% >NUL 2>NUL16+if 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+)27+28+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%29+goto end30+31+:help32+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%33+34+:end35+popdmodified:docs/Makefile+9 added-108 removed
1-# Makefile for Sphinx documentation1+# Minimal makefile for Sphinx documentation2 #3 4 # You can set these variables from the command line.5 SPHINXOPTS =6 SPHINXBUILD = sphinx-build7-PAPER =7+SOURCEDIR = .8 BUILDDIR = _build9 10-# Internal variables.11-PAPEROPT_a4 = -D latex_paper_size=a412-PAPEROPT_letter = -D latex_paper_size=letter13-ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .14-15-.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp epub latex changes linkcheck doctest16-10+# Put it first so that "make" without argument is like "make help".11 help: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)13 34-clean:35- -rm -rf $(BUILDDIR)/*14+.PHONY: help Makefile15 37-html:38- $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html39- @echo40- @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."41-42-dirhtml:43- $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml44- @echo45- @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."46-47-singlehtml:48- $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml49- @echo50- @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."51-52-pickle:53- $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle54- @echo55- @echo "Build finished; now you can process the pickle files."56-57-json:58- $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json59- @echo60- @echo "Build finished; now you can process the JSON files."61-62-htmlhelp: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."67-68-qthelp: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"76-77-devhelp: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"85-86-epub:87- $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub88- @echo89- @echo "Build finished. The epub file is in $(BUILDDIR)/epub."90-91-latex: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."97-98-latexpdf: 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."103-104-changes:105- $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes106- @echo107- @echo "The overview file is in $(BUILDDIR)/changes."108-109-linkcheck: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."114-115-doctest: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
1+Sphinx~=2.1.22+Pallets-Sphinx-Themes~=1.2.03+sphinxcontrib-log-cabinet~=1.0.14+sphinx-issues~=1.2.0modified:docs/templates.rst+98 added-38 removed
393 unmodified lines394 this template "extends" another template. When the template system evaluates395 this template, it first locates the parent. The extends tag should be the396 first tag in the template. Everything before it is printed out normally and397 may cause confusion. For details about this behavior and how to take398-advantage of it, see :ref:`null-master-fallback`.398+advantage of it, see :ref:`null-master-fallback`. Also a block will always be399+filled in regardless of whether the surrounding condition is evaluated to be true400+or false.401 402 The filename of the template depends on the template loader. For example, the403 :class:`FileSystemLoader` allows you to access other templates by giving the404 filename. You can access templates in subdirectories with a slash::21 unmodified lines426 427 Super Blocks428 ~~~~~~~~~~~~429 428-It's possible to render the contents of the parent block by calling `super`.430+It's possible to render the contents of the parent block by calling ``super()``.431 This gives back the results of the parent block::432 433 {% block sidebar %}434 <h3>Table Of Contents</h3>1 unmodified line436 {{ super() }}437 {% endblock %}438 439 440+Nesting extends441+~~~~~~~~~~~~~~~442+443+In the case of multiple levels of ``{% extends %}``,444+``super`` references may be chained (as in ``super.super()``)445+to skip levels in the inheritance tree.446+447+For example::448+449+ # parent.tmpl450+ body: {% block body %}Hi from parent.{% endblock %}451+452+ # child.tmpl453+ {% extends "parent.tmpl" %}454+ {% block body %}Hi from child. {{ super() }}{% endblock %}455+456+ # grandchild1.tmpl457+ {% extends "child.tmpl" %}458+ {% block body %}Hi from grandchild1.{% endblock %}459+460+ # grandchild2.tmpl461+ {% extends "child.tmpl" %}462+ {% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}463+464+465+Rendering ``child.tmpl`` will give466+``body: Hi from child. Hi from parent.``467+468+Rendering ``grandchild1.tmpl`` will give469+``body: Hi from grandchild1.``470+471+Rendering ``grandchild2.tmpl`` will give472+``body: Hi from grandchild2. Hi from parent.``473+474+475 Named Block End-Tags476 ~~~~~~~~~~~~~~~~~~~~477 478 Jinja2 allows you to put the name of the block after the end tag for better134 unmodified lines613 As variables in templates retain their object properties, it is possible to614 iterate over containers like `dict`::615 616 <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 lines1176 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).1179 1143-42 / 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).1180+42 / 123_456:1181+ Integers are whole numbers without a decimal part. The '_' character1182+ can be used to separate groups for legibility.1183 1184+42.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.1190+1191 ['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 lines1242 1243 /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``.)1246 1247 //1248 Divide two numbers and return the truncated integer result.1249 ``{{ 20 // 7 }}`` is ``2``.106 unmodified lines1356 1357 The `else` part is optional. If not provided, the else block implicitly1358 evaluates into an undefined object:1359 1360+.. sourcecode:: jinja1361+1362+ {{ "[{}]".format(page.title) if page.title }}1363+1364+1365+.. _python-methods:1366+1367+Python Methods1368+~~~~~~~~~~~~~~1369+1370+You can also use any of the methods of defined on a variable's type.1371+The value returned from the method invocation is used as the value of the expression.1372+Here is an example that uses methods defined on strings (where ``page.title`` is a string):1373+1374 .. code-block:: text1375 1321- {{ ('[%s]' % page.title) if page.title }}1376+ {{ page.title.capitalize() }}1377 1378+This also works for methods on user-defined types.1379+For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1380+you can do the following:1381 1382+.. code-block:: text1383+1384+ {{ f.bar() }}1385+1386+1387 .. _builtin-filters:1388 1389 List of Builtin Filters1390 -----------------------1391 1329-=================== =================== ================== ====================== ====================1330-Built-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_FILTERS1393 1394 1345-1346-.. jinjafilters::1347-1348-1395 .. _builtin-tests:1396 1397 List of Builtin Tests1398 ---------------------1399 1354-=================== ================== =================== ================ ================1355-Built-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_TESTS1401 1364-.. jinjatests::1402 1403 .. _builtin-globals:1404 1405 List of Global Functions251 unmodified lines1657 Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 01658 (See: :ref:`for-loop`).1659 1660 1661+Debug Statement1662+~~~~~~~~~~~~~~~1663+1664+If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be1665+available to dump the current context as well as the available filters1666+and tests. This is useful to see what's available to use in the template1667+without setting up a debugger.1668+1669+.. code-block:: html+jinja1670+1671+ <pre>{% debug %}</pre>1672+1673+.. code-block:: text1674+1675+ {'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']}1682+1683+1684 With Statement1685 ~~~~~~~~~~~~~~1686 1687 .. versionadded:: 2.374 unmodified linesmodified:ext/Vim/jinja.vim+3 added
80 unmodified lines81 syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment82 83 " Jinja comments84 syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment85+" help support folding for some setups86+setlocal commentstring={#%s#}87+setlocal comments=s:{#,e:#}88 89 " 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 linesmodified:ext/inlinegettext.py+1 added-1 removed
30 unmodified lines31 def filter_stream(self, stream):32 paren_stack = 033 34 for token in stream:35- if token.type is not 'data':35+ if token.type != 'data':36 yield token37 continue38 39 pos = 039 unmodified linesmodified:jinja2/__init__.py+3 added-3 removed
25 unmodified lines26 :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"31 32 # high level interface33 from jinja2.environment import Environment, Template34 6 unmodified lines41 from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache43 44 # undefined types45-from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46- make_logging_undefined45+from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46+ StrictUndefined, make_logging_undefined47 48 # exceptions49 from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \22 unmodified linesmodified:jinja2/bccache.py+5 added-6 removed
1 unmodified line2 """3 jinja2.bccache4 ~~~~~~~~~~~~~~5 6- 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.10 11 Situations where this is useful are often forking web applications that12 are initialized on the first request.282 unmodified lines295 the minimal interface required.296 297 Libraries compatible with this class:298 299- - `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/>`_301 302 (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 available57 unmodified linesmodified:jinja2/debug.py+11 added-5 removed
363 unmodified lines364 # try to get a tb_set_next implementation if we don't have transparent365 # proxies.366 tb_set_next = None367 if 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+ pass378+del _init_ugly_crapmodified:jinja2/exceptions.py+1 added-1 removed
48 unmodified lines49 # bogusly warns us about message being deprecated50 message = None51 52 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 = name89 unmodified linesmodified:jinja2/ext.py+54 added-3 removed
1 unmodified line2 """3 jinja2.ext4 ~~~~~~~~~~5 6- 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:8 9+ - An 18n support ``{% trans %}`` tag.10+ - A ``{% do %}`` tag.11+ - Loop control ``{% break %}`` and ``{% continue %}`` tags.12+ - A ``{% debug %}`` tag.13+14 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD.16 """17+import pprint18 import re19+from sys import version_info20 21 from jinja2 import nodes22 from 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_BLOCKS27 from jinja2.environment import Environment28+from jinja2.nodes import ContextReference29 from jinja2.runtime import concat30 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError31 from jinja2.utils import contextfunction, import_string, Markup32 from jinja2._compat import with_metaclass, string_types, iteritems33+from markupsafe import escape34 35 36 # the only real useful gettext functions for a Jinja template. Note37 # that ugettext must be assigned to gettext as Jinja doesn't support403 unmodified lines441 class AutoEscapeExtension(Extension):442 pass443 444 445+class DebugExtension(Extension):446+ """A ``{% debug %}`` tag that dumps the available variables,447+ filters, and tests.448+449+ .. code-block:: html+jinja450+451+ <pre>{% debug %}</pre>452+453+ .. code-block:: text454+455+ {'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']}462+463+ .. versionadded:: 2.11.0464+ """465+ tags = {'debug'}466+467+ 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)472+473+ 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+ }479+480+ # 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)485+486+487 def 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 string183 unmodified lines674 do = ExprStmtExtension675 loopcontrols = LoopControlExtension676 with_ = WithExtension677 autoescape = AutoEscapeExtension678+debug = DebugExtensionmodified:jinja2/filters.py+123 added-56 removed
57 unmodified lines58 to lowercase and returns other types as-is."""59 return value.lower() if isinstance(value, string_types) else value60 61 62-def make_attrgetter(environment, attribute, postprocess=None):62+def 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)69 70 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)73 74+ if default and isinstance(item, Undefined):75+ item = default76+77 if postprocess is not None:78 item = postprocess(item)79 80 return item81 82 return attrgetter83 84 85+def 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.90+91+ The value returned by the returned callable is a list of extracted92+ attribute values.93+94+ 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]98+99+ 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)105+106+ if postprocess is not None:107+ item_i = postprocess(item_i)108+109+ items[i] = item_i110+ return items111+112+ return attrgetter113+114+115+def _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]122+123+124 def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, '__html__'):127 value = value.__html__()151 unmodified lines279 return sorted(value.items(), key=sort_func, reverse=reverse)280 281 282 @environmentfilter246-def 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.283+def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):284+ """Sort an iterable using Python's :func:`sorted`.285 252- 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:: jinja287 288+ {% for city in cities|sort %}289+ ...290+ {% endfor %}291+292+ :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"``.298+299+ 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.302+303 .. sourcecode:: jinja304 258- {% for item in iterable|sort %}305+ {% for user in users|sort(attribute="name")|sort(reverse=true, attribute="age") %}306 ...307 {% endfor %}308 262- 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.311 312 .. sourcecode:: jinja313 267- {% for item in iterable|sort(attribute='date') %}314+ {% for user users|sort(attribute="age,name") %}315 ...316 {% endfor %}317 318+ .. versionchanged:: 2.11.0319+ The ``attribute`` parameter can be a comma separated list of320+ attributes, e.g. ``"age,name"``.321+322 .. 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)330 331 332 @environmentfilter333 def 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.335 336 .. sourcecode:: jinja337 287- {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}338+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}339 -> ['foo', 'bar', 'foobar']340 341 The unique items are yielded in the same order as their first occurrence in342 the iterable passed to the filter.23 unmodified lines366 except StopIteration:367 return environment.undefined('No aggregated item, sequence was empty.')368 369 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)375 376 42 unmodified lines419 420 .. sourcecode:: jinja421 422 {{ ''|default('the string was empty', true) }}423+424+ .. 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 value323 unmodified lines756 'arguments at the same time')757 return soft_unicode(value) % (kwargs or args)758 759 702-def do_trim(value):703- """Strip leading and trailing whitespace."""704- return soft_unicode(value).strip()760+def do_trim(value, chars=None):761+ """Strip leading and trailing characters, by default whitespace."""762+ return soft_unicode(value).strip(chars)763 764 765 def do_striptags(value):766 """Strip SGML/XML tags and replace adjacent whitespace by one space.9 unmodified lines776 three ul tags that represent columns:777 778 .. sourcecode:: html+jinja779 722- <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 lines879 _GroupTuple = namedtuple('_GroupTuple', ['grouper', 'list'])880 _GroupTuple.__repr__ = tuple.__repr__881 _GroupTuple.__str__ = tuple.__str__882 883+884 @environmentfilter885 def 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.891 829- 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.895 896 .. sourcecode:: html+jinja897 836- <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>905 845- 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.909 910 .. sourcecode:: html+jinja911 850- <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>915 856- 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.859-916 .. 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 lines1015 .. sourcecode:: jinja1016 1017 Users on this page: {{ users|map(attribute='username')|join(', ') }}1018 1019+ You can specify a ``default`` value to use if an object in the list1020+ does not have the given attribute.1021+1022+ .. sourcecode:: jinja1023+1024+ {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1025+1026 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:1029 1030 .. sourcecode:: jinja1031 1032 Users on this page: {{ titles|map('lower')|join(', ') }}1033 1034+ .. versionchanged:: 2.11.01035+ Added the ``default`` parameter.1036+1037 .. versionadded:: 2.71038 """1039 seq, func = prepare_map(args, kwargs)1040 if seq:118 unmodified lines1159 1160 def prepare_map(args, kwargs):1161 context = args[0]1162 seq = args[1]1163+ default = None1164 1165 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 linesmodified:jinja2/lexer.py+21 added-6 removed
13 unmodified lines14 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD, see LICENSE for more details.16 """17 import re18+from ast import literal_eval19 from collections import deque20 from operator import itemgetter21 22 from jinja2._compat import implements_iterator, intern, iteritems, text_type23 from jinja2.exceptions import TemplateSyntaxError24 from jinja2.utils import LRUCache25 26+from ast import literal_eval # to support scientific notation27+28 # cache for the lexers. Exists in order to be able to have multiple29 # environments with the same lexer30 _lexer_cache = LRUCache(50)31 32 # static regular expressions33 whitespace_re = re.compile(r'\s+', re.U)34+newline_re = re.compile(r'(\r\n|\r|\n)')35 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"36 r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)33-integer_re = re.compile(r'\d+')37+integer_re = re.compile(r'(\d+_)*\d+')38+float_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+)51 52 try:53 # check if this Python supports Unicode identifiers54 compile('föö', '<unknown>', 'eval')13 unmodified lines68 import jinja269 del jinja2._identifier70 del _identifier71 55-float_re = re.compile(r'(?<!\.)\d+\.\d+')56-newline_re = re.compile(r'(\r\n|\r|\n)')57-72 # internal the tokens and keep references to them73 TOKEN_ADD = intern('add')74 TOKEN_ASSIGN = intern('assign')75 TOKEN_COLON = intern('colon')497 unmodified lines573 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 linesmodified:jinja2/meta.py+1 added-1 removed
27 unmodified lines28 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)34 35 36 def find_undeclared_variables(ast):70 unmodified linesmodified:jinja2/parser.py+3 added-1 removed
839 unmodified lines840 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 linesmodified:jinja2/runtime.py+38 added-9 removed
56 unmodified lines57 58 59 def 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 = vars334 unmodified lines400 "forgot the 'recursive' modifier.")401 return self._recurse(iterable, self._recurse, self.depth0 + 1)402 403 # 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 loop407 408 def __repr__(self):90 unmodified lines499 # 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].autoescape67 unmodified lines584 585 @implements_to_string586 class 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`:589 590 >>> foo = Undefined(name='foo')591 >>> str(foo)592 ''15 unmodified lines608 609 @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_name131 unmodified lines748 749 return LoggingUndefined750 751 752+# 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.755+class ChainableUndefined(Undefined):756+ """An undefined that is chainable, where both ``__getattr__`` and757+ ``__getitem__`` return itself rather than raising an758+ :exc:`UndefinedError`.759+760+ >>> 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 undefined767+768+ .. versionadded:: 2.11.0769+ """770+ __slots__ = ()771+772+ def __html__(self):773+ return self.__str__()774+775+ def __getattr__(self, _):776+ return self777+778+ __getitem__ = __getattr__779+780+781 @implements_to_string782 class DebugUndefined(Undefined):783 """An undefined that returns the debug info when printed.784 47 unmodified lines832 833 834 # remove remaining slots attributes, after the metaclass did the magic they835 # are unneeded and irritating as they contain wrong data for the subclasses.808-del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__836+del Undefined.__slots__, ChainableUndefined.__slots__, \837+ DebugUndefined.__slots__, StrictUndefined.__slots__modified:jinja2/sandbox.py+8 added-4 removed
14 unmodified lines15 import types16 import operator17 from jinja2.environment import Environment18 from jinja2.exceptions import SecurityError19-from jinja2._compat import string_types, PY2, abc19+from jinja2._compat import string_types, PY2, abc, range_type20 from jinja2.utils import Markup21 22 from markupsafe import EscapeFormatter23 from string import Formatter121 unmodified lines145 def 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)150+151 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+ )156+157 return rng158 159 160 def unsafe(f):328 unmodified linesmodified:jinja2/utils.py+15 added-13 removed
9 unmodified lines10 """11 import re12 import json13 import errno14+import warnings15 from collections import deque16 from threading import Lock17 from jinja2._compat import text_type, string_types, implements_iterator, \18 url_quote, abc116 unmodified lines135 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 lines354 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()363 364 def clear(self):365 """Clear the cache."""366 self._wlock.acquire()63 unmodified lines430 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 lines450 return [x[1] for x in self.items()]451 452 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()459+460+ def itervalues(self):461+ """Iterate over all values."""462 return iter(self.values())463 464 def keys(self):465 """Return a list of all keys ordered by most recent usage."""7 unmodified lines473 474 __iter__ = iterkeys475 476 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 linesmodified:tests/conftest.py+44 added-1 removed
14 unmodified lines15 from jinja2.utils import have_async_gen16 from jinja2 import Environment17 18 19-def pytest_ignore_collect(path, config):19+def pytest_ignore_collect(path):20 if 'async' in path.basename and not have_async_gen:21 return True22 return False23 24 25+def 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')66+67+68 @pytest.fixture69 def env():70 '''returns a new environment.71 '''49 unmodified linesmodified:tests/test_api.py+52 added-7 removed
11 unmodified lines12 import tempfile13 import shutil14 15 import pytest16-from jinja2 import Environment, Undefined, DebugUndefined, \17- StrictUndefined, UndefinedError, meta, \16+from jinja2 import Environment, Undefined, ChainableUndefined, \17+ DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19 from jinja2.compiler import CodeGenerator20 from jinja2.runtime import Context21 from jinja2.utils import Cycler81 unmodified lines103 assert t.render(foo='<foo>') == '<foo>'104 t = env.from_string('{{ foo }}')105 assert t.render(foo='<foo>') == '<foo>'106 107+ def test_sandbox_max_range(self, env):108+ from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE109 110+ env = SandboxedEnvironment()111+ t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")112+113+ with pytest.raises(OverflowError):114+ t.render(total=MAX_RANGE + 1)115+116+117 @pytest.mark.api118 @pytest.mark.meta119 class TestMeta(object):120 8 unmodified lines129 '{% endfor %}')130 x = meta.find_undeclared_variables(ast)131 assert x == set(['bar', 'seq', 'muh'])132 133+ ast = env.parse('{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}')134+ x = meta.find_undeclared_variables(ast)135+ assert x == set(['foo'])136+137 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 lines222 t = Template('A{{ test().missingattribute }}B')223 pytest.raises(UndefinedError, t.render, test=test)224 225 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"228 229 def test_logging_undefined(self):230 _messages = []231 33 unmodified lines265 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__')276 277+ 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__')290+291+ # 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'299+300 def test_debug_undefined(self):301 env = Environment(undefined=DebugUndefined)302 assert env.from_string('{{ missing }}').render() == '{{ missing }}'303 pytest.raises(UndefinedError,3 unmodified lines307 == '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__')315 316 def test_strict_undefined(self):317 env = Environment(undefined=StrictUndefined)318 pytest.raises(UndefinedError, env.from_string('{{ missing }}').render)8 unmodified lines327 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__')333 334 def test_indexing_gives_undefined(self):335 t = Template("{{ var[42].foo }}")336 pytest.raises(UndefinedError, t.render, var=0)49 unmodified linesmodified:tests/test_ext.py+8 added
238 unmodified lines239 ext = list(env.iter_extensions())240 assert ext[0].__class__ is T1241 assert ext[1].__class__ is T2242 243+ def test_debug(self):244+ env = Environment(extensions=['jinja2.ext.debug'])245+ t = env.from_string('Hello\n{% debug %}\nGoodbye')246+ out = t.render()247 248+ for value in ("context", "cycler", "filters", "abs", "tests", "!="):249+ assert "'{}'".format(value) in out250+251+252 @pytest.mark.ext253 class TestInternationalization(object):254 255 def test_trans(self):341 unmodified linesmodified:tests/test_filters.py+105 added-13 removed
21 unmodified lines22 def __str__(self):23 return text_type(self.value)24 25 26+@implements_to_string27+class Magic2(object):28+ def __init__(self, value1, value2):29+ self.value1 = value130+ self.value2 = value231+32+ def __str__(self):33+ return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))34+35+36 @pytest.mark.filter37 class TestFilter(object):38 39 def test_filter_calling(self, env):44 unmodified lines84 tmpl = env.from_string('''{{ '<">&'|escape }}''')85 out = tmpl.render()86 assert out == '<">&'87 88+ @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 == expect95+96 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 lines140 tmpl = env.from_string('{{ foo|first }}')141 out = tmpl.render(foo=list(range(10)))142 assert out == '0'143 126- 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() == expect150 151+ def test_float_default(self, env):152+ t = env.from_string("{{ value|float(default=1.0) }}")153+ assert t.render(value="abc") == "1.0"154+155 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 lines189 def test_indentfirst_deprecated(self, env):190 with pytest.warns(DeprecationWarning):191 env.from_string('{{ "jinja"|indent(indentfirst=true) }}').render()192 193+ @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() == expect205+206+ @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() == expect217+171- 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"221+222+ def test_int_special_method(self, env):223 class IntIsh(object):224 def __int__(self):225 return 42226 176- 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"229 230 def test_join(self, env):231 tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')232 out = tmpl.render()230 unmodified lines463 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'466 467+ 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]'470+471+ 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)')476+477+ 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)')481+482+ 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])')489+490 def test_unique(self, env):491 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')492 assert t.render() == "bA"493 141 unmodified lines635 env = Environment()636 tmpl = env.from_string('{{ none|map("upper")|list }}')637 assert tmpl.render() == '[]'638 639+ def test_map_default(self, env):640+ class Fullname(object):641+ def __init__(self, firstname, lastname):642+ self.firstname = firstname643+ self.lastname = lastname644+645+ class Firstname(object):646+ def __init__(self, firstname):647+ self.firstname = firstname648+649+ 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"660+661 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 linesmodified:tests/test_imports.py-2 removed
137 unmodified lines138 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')144 145 def test_include_ignoring_missing(self, test_env):33 unmodified linesmodified:tests/test_lexnparse.py+33 added-3 removed
334 unmodified lines335 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'338 339- 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() == value343 344+ @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() == expect364+365 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 lines524 env = Environment(lstrip_blocks=True, trim_blocks=False)525 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')526 assert tmpl.render() == " \n "527 528+ 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 "535+536 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 linesmodified:tests/test_regression.py+9 added
481 unmodified lines482 def test_empty_if(self, env):483 t = env.from_string('{% if foo %}{% else %}42{% endif %}')484 assert t.render(foo=False) == '42'485 486+ 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'489+490 def test_set_and_include(self):491 env = Environment(loader=DictLoader({492 'inc': 'bar',493 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}'48 unmodified lines542 tmpl = env.from_string('''543 {%- for value in values recursive %}1{% else %}0{% endfor -%}544 ''')545 assert tmpl.render(values=[]) == '0'546+547+ 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 lines139 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'145 146 def test_unary_operator_intercepting(self, env):147 def disable_op(arg):148 raise TemplateRuntimeError('that operator so does not work')3 unmodified lines152 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'158 159 160 @pytest.mark.sandbox161 class TestStringFormat(object):39 unmodified linesmodified:tests/test_utils.py+116 added-4 removed
6 unmodified lines7 8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11+12+from collections import deque13 import gc14+import pickle15+import random16 17 import pytest18 15-import pickle16-19+from jinja2._compat import string_types, range_type20 from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18- select_autoescape21+ select_autoescape, generate_lorem_ipsum, missing, consume22+from markupsafe import Markup23 20-24 @pytest.mark.utils25 @pytest.mark.lrucache26 class TestLRUCache(object):27 6 unmodified lines34 d["d"] = 435 assert len(d) == 336 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d37 38+ def test_itervalue_deprecated(self):39+ cache = LRUCache(3)40+ cache["a"] = 141+ cache["b"] = 242+ with pytest.deprecated_call():43+ cache.itervalue()44+45+ 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 values53+54+ def test_itervalues_empty(self):55+ cache = LRUCache(2)56+ values = [v for v in cache.itervalues()]57+ assert len(values) == 058+59 def test_pickleable(self):60 cache = LRUCache(2)61 cache["foo"] = 4262 cache["bar"] = 234 unmodified lines67 assert copy.capacity == cache.capacity68 assert copy._mapping == cache._mapping69 assert copy._queue == cache._queue70 71+ 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([])}78 79+ 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}>")86+87+ 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']97+98+ # 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']105+106+ 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) == 2114+115+116 @pytest.mark.utils117 @pytest.mark.helpers118 class TestHelpers(object):119 31 unmodified lines151 target = "<script>"152 assert urlize(url, target=target) == ('<a href="http://example.org"'153 ' target="<script>">'154 'http://example.org</a>')155+156+157+@pytest.mark.utils158+@pytest.mark.loremIpsum159+class 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)163+164+ 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)167+168+ 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) * 2173+174+ 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 - 1180+181+ 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 - 1187+188+189+def test_missing():190+ """Test the repr of missing."""191+ assert repr(missing) == u'missing'192+193+def 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
1+trigger:2+ - master3+ - '*.x'4+5+variables:6+ vmImage: ubuntu-latest7+ python.version: 3.78+ TOXENV: py,coverage-ci9+ hasTestResults: true10+11+strategy: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: false33+34+pool:35+ vmImage: $[ variables.vmImage ]36+37+steps:38+ - task: UsePythonVersion@039+ inputs:40+ versionSpec: $(python.version)41+ displayName: Use Python $(python.version)42+43+ - script: pip --disable-pip-version-check install -U tox44+ displayName: Install tox45+46+ - script: tox -s false -- --junit-xml=test-results.xml47+ displayName: Run tox48+49+ - task: PublishTestResults@250+ inputs:51+ testResultsFiles: test-results.xml52+ testRunTitle: $(Agent.JobName)53+ condition: eq(variables['hasTestResults'], 'true')54+ displayName: Publish test results55+56+ - task: PublishCodeCoverageResults@157+ inputs:58+ codeCoverageTool: Cobertura59+ summaryFileLocation: coverage.xml60+ condition: eq(variables['hasTestResults'], 'true')61+ displayName: Publish coverage resultsdeleted:.coveragerc-11 removed
1-[run]2-branch = True3-source =4- jinja25- tests6-7-[paths]8-source =9- jinja210- .tox/*/lib/python*/site-packages/jinja211- .tox/pypy/site-packages/jinja2modified:.gitignore+1 added
8 unmodified lines9 .DS_Store10 .tox/11 .cache/12 .idea/13+env/14 venv/15 venv-*/16 .coverage17 .coverage.*2 unmodified linesdeleted:.travis.yml-46 removed
1-dist: xenial2-sudo: false3-language: python4-5-python:6- - 3.77- - 3.68- - 3.59- - 3.410- - 2.711- - pypy3.5-6.012- - pypy2.7-6.013-14-env:15- - TOXENV=py,codecov16-17-matrix:18- include:19- - python: nightly20- env: TOXENV=py21- - python: 3.622- env: TOXENV=docs-html23-24-install:25- - pip install tox26-27-script:28- - tox29-30-cache:31- - pip32-33-branches:34- only:35- - master36- - /^.*-maintenance$/37-38-notifications:39- email: false40- irc:41- channels:42- - "chat.freenode.net#pocoo"43- on_success: change44- on_failure: always45- use_notice: true46- skip_join: truedeleted:AUTHORS-35 removed
1-Jinja is written and maintained by the Jinja Team and various2-contributors:3-4-Lead Developer:5-6-- Armin Ronacher <armin.ronacher@active-4.com>7-8-Developers:9-10-- Christoph Hack11-- Georg Brandl12-13-Contributors:14-15-- Bryan McLemore16-- Mickaël Guérin <kael@crocobox.org>17-- Cameron Knight18-- Lawrence Journal-World.19-- David Cramer20-- Adrian Mönnich (ThiefMaster)21-22-Patches and suggestions:23-24-- 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:: jinja22 3-Jinja Changelog4-===============5-6-3 Version 2.114 ------------5 10-unreleased6+Unreleased7 12-- 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`30 18-.. _#765: https://github.com/pallets/jinja/issues/76531 32+Version 2.10.333+--------------34 35+Released 2019-10-0436+37+- Fix a typo in Babel entry point in ``setup.py`` that was preventing38+ installation.39+40+41+Version 2.10.242+--------------43+44+Released 2019-10-0445+46+- 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`51+52+53 Version 2.10.154 --------------55 56 Released 2019-04-065 unmodified lines62 63 Version 2.1064 ------------65 34-released on November 8th 201766+Released 2017-11-0867 36-- 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`107 73-.. _#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/759108 86-109 Version 2.9.6110 -------------111 90-(bugfix release, released on April 3rd 2017)112+Released 2017-04-03113 92-- Fixed custom context behavior in fast resolve mode (#675)114+- Fixed custom context behavior in fast resolve mode :issue:`675`115 116 117 Version 2.9.5118 -------------119 98-(bugfix release, released on January 28th 2017)120+Released 2017-01-28121 100-- 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`137 138 139 Version 2.9.4140 -------------141 118-(bugfix release, released on January 10th 2017)142+Released 2017-01-10143 120-- 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.154 155 156 Version 2.9.3157 -------------158 134-(bugfix release, released on January 8th 2017)159+Released 2017-01-08160 136-- 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.176 177 178 Version 2.9.2179 -------------180 155-(bugfix release, released on January 8th 2017)181+Released 2017-01-08182 157-- 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`193 194 195 Version 2.9.1196 -------------197 171-(bugfix release, released on January 7th 2017)198+Released 2017-01-07199 173-- 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.203 204 205 Version 2.9206 -----------180-(codename Derivation, released on January 7th 2017)207 182-- 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.208+Released 2017-01-07, codename Derivation209 210+- 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.253 254+255 Version 2.8.1256 -------------257 228-(bugfix release, released on December 29th 2016)258+Released 2016-12-29259 230-- 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.265 266 267 Version 2.8268 -----------269 240-(codename Replacement, released on July 26th 2015)270+Released 2015-07-26, codename Replacement271 242-- 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.304 305 306 Version 2.7.3307 -------------308 276-(bugfix release, released on June 6th 2014)309+Released 2014-06-06310 278-- 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.313 314 315 Version 2.7.2316 -------------317 285-(bugfix release, released on January 10th 2014)318+Released 2014-01-10319 287-- 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.325 293-.. _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=734747327 328 329 Version 2.7.1330 -------------331 299-(bugfix release, released on August 7th 2013)332+Released 2013-08-07333 301-- 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.344 345 346 Version 2.7347 -----------348 316-(codename Translation, released on May 20th 2013)349+Released 2013-05-20, codename Translation350 318-- 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.379 380 381 Version 2.6382 -----------383 349-(codename Convolution, released on July 24th 2011)384+Released 2011-07-24, codename Convolution385 351-- 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.417 418 419 Version 2.5.5420 -------------421 385-(re-release of 2.5.4 with built documentation removed for filesize.386- Released on October 18th 2010)422+Released 2010-10-18423 388-- built documentation is no longer part of release.424+- Built documentation is no longer part of release.425 426 427 Version 2.5.4428 -------------429 394-(bugfix release, released on October 17th 2010)430+Released 2010-10-17431 396-- 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.435 436 437 Version 2.5.3438 -------------439 404-(bugfix release, released on October 17th 2010)440+Released 2010-10-17441 406-- 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)".446 447 448 Version 2.5.2449 -------------414-(bugfix release, released on August 18th 2010)450 416-- 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.451+Released 2010-08-18452 453+- 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.456 457+458 Version 2.5.1459 -------------460 424-(bugfix release, released on August 17th 2010)461+Released 2010-08-17462 426-- 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.477 478 479 Version 2.5480 -----------481 445-(codename Incoherence, released on May 29th 2010)482+Released 2010-05-29, codename Incoherence483 447-- 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.492 493 494 Version 2.4.1495 -------------496 460-(bugfix release, released on April 20th 2010)497+Released 2010-04-20498 462-- fixed an error reporting bug for undefineds.499+- Fixed an error reporting bug for undefined.500 501 502 Version 2.4503 -----------504 468-(codename Correlation, released on April 13th 2010)505+Released 2010-04-13, codename Correlation506 470-- 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.519 520 521 Version 2.3.1522 -------------523 487-(bugfix release, released on February 19th 2010)524+Released 2010-02-19525 489-- 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.4528 529 530 Version 2.3531 -----------532 496-(codename 3000 Pythons, released on February 10th 2010)533+Released 2010-02-10, codename 3000 Pythons534 498-- 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.549 550 551 Version 2.2.1552 -------------553 519-(bugfix release, released on September 14th 2009)554+Released 2009-09-14555 521-- fixes some smaller problems for Jinja2 on Jython.556+- Fixes some smaller problems for Jinja2 on Jython.557 558 559 Version 2.2560 -----------561 527-(codename Kong, released on September 13th 2009)562+Released 2009-09-13, codename Kong563 529-- 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.584 585 586 Version 2.1.1587 -------------588 553-(bugfix release, released on December 25th 2008)589+Released 2008-12-25590 555-- Fixed a translation error caused by looping over empty recursive loops.591+- Fixed a translation error caused by looping over empty recursive592+ loops.593 594 595 Version 2.1596 -----------597 561-(codename Yasuzō, released on November 23rd 2008)598+Released 2008-11-23, codename Yasuzō599 563-- 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 urlize628 629 630 Version 2.0631 -----------632 594-(codename jinjavitus, released on July 17th 2008)633+Released 2008-07-17, codename Jinjavitus634 596-- 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 finalizer655 602- 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 finalizer656 616-657 Version 2.0rc1658 --------------659 620-(no codename, released on June 9th 2008)660+Released 2008-06-09661 622-- first release of Jinja2662+- First release of Jinja2added:CODE_OF_CONDUCT.md+76 added
1+# Contributor Covenant Code of Conduct2+3+## Our Pledge4+5+In the interest of fostering an open and welcoming environment, we as6+contributors and maintainers pledge to making participation in our project and7+our community a harassment-free experience for everyone, regardless of age, body8+size, disability, ethnicity, sex characteristics, gender identity and expression,9+level of experience, education, socio-economic status, nationality, personal10+appearance, race, religion, or sexual identity and orientation.11+12+## Our Standards13+14+Examples of behavior that contributes to creating a positive environment15+include:16+17+* 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 members22+23+Examples of unacceptable behavior by participants include:24+25+* 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 setting33+34+## Our Responsibilities35+36+Project maintainers are responsible for clarifying the standards of acceptable37+behavior and are expected to take appropriate and fair corrective action in38+response to any instances of unacceptable behavior.39+40+Project maintainers have the right and responsibility to remove, edit, or41+reject comments, commits, code, wiki edits, issues, and other contributions42+that are not aligned to this Code of Conduct, or to ban temporarily or43+permanently any contributor for other behaviors that they deem inappropriate,44+threatening, offensive, or harmful.45+46+## Scope47+48+This Code of Conduct applies both within project spaces and in public spaces49+when an individual is representing the project or its community. Examples of50+representing a project or community include using an official project e-mail51+address, posting via an official social media account, or acting as an appointed52+representative at an online or offline event. Representation of a project may be53+further defined and clarified by project maintainers.54+55+## Enforcement56+57+Instances of abusive, harassing, or otherwise unacceptable behavior may be58+reported by contacting the project team at report@palletsprojects.com. All59+complaints will be reviewed and investigated and will result in a response that60+is deemed necessary and appropriate to the circumstances. The project team is61+obligated to maintain confidentiality with regard to the reporter of an incident.62+Further details of specific enforcement policies may be posted separately.63+64+Project maintainers who do not follow or enforce the Code of Conduct in good65+faith may face temporary or permanent repercussions as determined by other66+members of the project's leadership.67+68+## Attribution69+70+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html72+73+[homepage]: https://www.contributor-covenant.org74+75+For answers to common questions about this code of conduct, see76+https://www.contributor-covenant.org/faqdeleted:LICENSE-31 removed
1-Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.2-3-Some rights reserved.4-5-Redistribution and use in source and binary forms, with or without6-modification, are permitted provided that the following conditions are7-met:8-9- * Redistributions of source code must retain the above copyright10- notice, this list of conditions and the following disclaimer.11-12- * 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.16-17- * The names of the contributors may not be used to endorse or18- promote products derived from this software without specific19- prior written permission.20-21-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR24-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT27-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,28-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY29-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT30-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE31-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:LICENSE.rst+28 added
1+Copyright 2007 Pallets2+3+Redistribution and use in source and binary forms, with or without4+modification, are permitted provided that the following conditions are5+met:6+7+1. Redistributions of source code must retain the above copyright8+ notice, this list of conditions and the following disclaimer.9+10+2. 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.13+14+3. 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.17+18+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.deleted:Makefile-21 removed
1-test:2- py.test tests --tb=short3-4-develop:5- pip install --editable .6-7-tox-test:8- @tox9-10-release:11- python scripts/make-release.py12-13-upload-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/20-21-.PHONY: testmodified:MANIFEST.in+1 added-2 removed
1-include AUTHORS CHANGES.rst LICENSE2-global-exclude *.py[co]1+include CHANGES.rst tox.ini2 graft artwork3 graft docs4 prune docs/_build5 graft examples2 unmodified linesmodified:README.rst+50 added-35 removed
1-Jinja22-~~~~~~1+Jinja2+=====3 4-Jinja2 is a template engine written in pure Python. It provides a5-`Django`_ inspired non-XML syntax but supports inline expressions and6-an optional `sandboxed`_ environment.4+Jinja is a fast, expressive, extensible templating engine. Special5+placeholders in the template allow writing code similar to Python6+syntax. Then the template is passed data to render the final document.7 8-Nutshell9---------8+It includes:9 11-Here 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.23 24+Jinja's philosophy is that while application logic belongs in Python if25+possible, it shouldn't make the template designer's job difficult by26+restricting functionality too much.27+28+29+Installing30+----------31+32+Install and update using `pip`_:33+34+.. code-block:: text35+36+ $ pip install -U Jinja237+38+.. _pip: https://pip.pypa.io/en/stable/quickstart/39+40+41+In A Nutshell42+-------------43+44 .. code-block:: jinja45 15- {% 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 %}55 25-Philosophy26-----------56 28-Application logic is for the controller, but don't make the template designer's29-life difficult by restricting functionality too much.57+Links58+-----59 31-For more information visit the new `Jinja2 webpage`_ and `documentation`_.32-33-The `Jinja2 tip`_ is installable via ``pip`` with ``pip install34-https://github.com/pallets/jinja/zipball/master``.35-36-.. _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-install41-42-Builds43-------44-45-+---------------------+------------------------------------------------------------------------------+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/t6rrQZHmodified:setup.cfg+16 added-5 removed
1-[bdist_wheel]2-universal = 13-1 [metadata]5-license_file = LICENSE2+license_file = LICENSE.rst3 4+[bdist_wheel]5+universal = true6+7 [tool:pytest]8-minversion = 3.08 testpaths = tests9+10+[coverage:run]11+branch = True12+source =13+ jinja214+ tests15+16+[coverage:paths]17+source =18+ src/jinja219+ .tox/*/lib/python*/site-packages/jinja220+ .tox/*/site-packages/jinja2modified:setup.py+45 added-73 removed
1-# -*- coding: utf-8 -*-2-"""3-Jinja24-~~~~~~1+import io2+import re3 6-Jinja2 is a template engine written in pure Python. It provides a7-`Django`_ inspired non-XML syntax but supports inline expressions and8-an optional `sandboxed`_ environment.9-10-Nutshell11---------12-13-Here a small example of a Jinja template::14-15- {% 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 %}24-25-Philosophy26-----------27-28-Application logic is for the controller but don't try to make the life29-for the template designer too hard by giving him too few functionality.30-31-For more information visit the new `Jinja2 webpage`_ and `documentation`_.32-33-.. _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-"""4+from setuptools import find_packages5 from setuptools import setup6 7+with io.open("README.rst", "rt", encoding="utf8") as f:8+ readme = f.read()9 10+with io.open("jinja2/__init__.py", "rt", encoding="utf8") as f:11+ version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)12+13 setup(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]2 envlist =3- py{37,36,35,34,27,py3,py}3+ py{37,36,35,27,py3,py}4 docs-html5- coverage-report5+ coverage6+skip_missing_interpreters = true7 8 [testenv]8-passenv = LANG9-usedevelop = true9 deps =11- pytest>=3,<3.710 coverage11+ pytest12+commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}13 14-commands = coverage run -p -m pytest {posargs}15-14 [testenv:docs-html]17-deps = sphinx18-commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html15+deps =16+ Sphinx17+ Pallets-Sphinx-Themes18+ sphinxcontrib-log-cabinet19+ sphinx-issues20+commands = sphinx-build -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html21 20-[testenv:docs-linkcheck]21-deps = sphinx22-commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck23-24-[testenv:coverage-report]22+[testenv:coverage]23 deps = coverage24 skip_install = true25 commands =26 coverage combine29- coverage report27 coverage html28+ coverage report29 32-[testenv:codecov]33-passenv = CI TRAVIS TRAVIS_*34-deps = codecov30+[testenv:coverage-ci]31+deps = coverage32 skip_install = true33 commands =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