Skip to content
Myr

Merge pull request #1617 from pallets/docs-prose

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

rewrite non-technical documentation

authored by David Lord · committed by GitHub · parents 350bc53, 4b63cd8 · Browse files · 5 files+199 added−282 removed
This commit

State

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

Diff stats

5 files+199 added−282 removed

  • other:+199 added−282 removed

5 files+199 added−282 removed

modified:docs/api.rst+11 added-8 removed
408 unmodified lines
409410 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)411412413.. admonition:: Implementation413The context is immutable, it prevents modifications, and if it is414modified somehow despite that those changes may not show up. For415performance, Jinja does not use the context as data storage for, only as416a primary data source. Variables that the template does not define are417looked up in the context, but variables the template does define are418stored locally.419415 Context is immutable for the same reason Python's frame locals are416 immutable inside functions. Both Jinja and Python are not using the417 context / frame locals as data storage for variables but only as primary418 data source.420Instead of modifying the context directly, a function should return421a value that can be assigned to a variable within the template itself.422420 When a template accesses a variable the template does not define, Jinja421 looks up the variable in the context, after that the variable is treated422 as if it was defined in the template.423.. code-block:: jinja424425 {% set comments = get_latest_comments() %}426427428.. _loaders:429430Loaders431-------
491 unmodified lines
modified:docs/faq.rst+50 added-130 removed
1Frequently Asked Questions2==========================34This page answers some of the often asked questions about Jinja.46.. highlight:: html+jinja75Why is it called Jinja?6-----------------------711The name Jinja was chosen because it's the name of a Japanese temple and12temple and template share a similar pronunciation. It is not named after13the city in Uganda.8"Jinja" is a Japanese `Shinto shrine`_, or temple, and temple and9template share a similar English pronunciation. It is not named after10the `city in Uganda`_.1115How fast is it?16---------------12.. _Shinto shrine: https://en.wikipedia.org/wiki/Shinto_shrine13.. _city in Uganda: https://en.wikipedia.org/wiki/Jinja%2C_Uganda1418We really hate benchmarks especially since they don't reflect much. The19performance of a template depends on many factors and you would have to20benchmark different engines in different situations. The benchmarks from the21testsuite show that Jinja has a similar performance to `Mako`_ and is between2210 and 20 times faster than Django's template engine or Genshi. These numbers23should be taken with tons of salt as the benchmarks that took these numbers24only test a few performance related situations such as looping. Generally25speaking the performance of a template engine doesn't matter much as the26usual bottleneck in a web application is either the database or the application27code.1529.. _Mako: https://www.makotemplates.org/16How fast is Jinja?17------------------1831How Compatible is Jinja with Django?32------------------------------------19Jinja is relatively fast among template engines because it compiles and20caches template code to Python code, so that the template does not need21to be parsed and interpreted each time. Rendering a template becomes as22close to executing a Python function as possible.2334The default syntax of Jinja matches Django syntax in many ways. However35this similarity doesn't mean that you can use a Django template unmodified36in Jinja. For example filter arguments use a function call syntax rather37than a colon to separate filter name and arguments. Additionally the38extension interface in Jinja is fundamentally different from the Django one39which means that your custom tags won't work any longer.24Jinja also makes extensive use of caching. Templates are cached by name25after loading, so future uses of the template avoid loading. The26template loading itself uses a bytecode cache to avoid repeated27compiling. The caches can be external to persist across restarts.28Templates can also be precompiled and loaded as fast Python imports.2941Generally speaking you will use much less custom extensions as the Jinja42template system allows you to use a certain subset of Python expressions43which can replace most Django extensions. For example instead of using44something like this::30We dislike benchmarks because they don't reflect real use. Performance31depends on many factors. Different engines have different default32configurations and tradeoffs that make it unclear how to set up a useful33comparison. Often, database access, API calls, and data processing have34a much larger effect on performance than the template engine.3546 {% load comments %}47 {% get_latest_comments 10 as latest_comments %}48 {% for comment in latest_comments %}49 ...50 {% endfor %}3652You will most likely provide an object with attributes to retrieve53comments from the database::37Isn't it a bad idea to put logic in templates?38----------------------------------------------3955 {% for comment in models.comments.latest(10) %}56 ...57 {% endfor %}5859Or directly provide the model for quick testing::6061 {% for comment in Comment.objects.order_by('-pub_date')[:10] %}62 ...63 {% endfor %}6465Please keep in mind that even though you may put such things into templates66it still isn't a good idea. Queries should go into the view code and not67the template!6869Isn't it a terrible idea to put Logic into Templates?70-----------------------------------------------------7140Without a doubt you should try to remove as much logic from templates as73possible. But templates without any logic mean that you have to do all74the processing in the code which is boring and stupid. A template engine75that does that is shipped with Python and called `string.Template`. Comes76without loops and if conditions and is by far the fastest template engine77you can get for Python.41possible. With less logic, the template is easier to understand, has42fewer potential side effects, and is faster to compile and render. But a43template without any logic means processing must be done in code before44rendering. A template engine that does that is shipped with Python,45called :class:`string.Template`, and while it's definitely fast it's not46convenient.4779So some amount of logic is required in templates to keep everyone happy.80And Jinja leaves it pretty much to you how much logic you want to put into81templates. There are some restrictions in what you can do and what not.48Jinja's features such as blocks, statements, filters, and function calls49make it much easier to write expressive templates, with very few50restrictions. Jinja doesn't allow arbitrary Python code in templates, or51every feature available in the Python language. This keeps the engine52easier to maintain, and keeps templates more readable.5383Jinja neither allows you to put arbitrary Python code into templates nor84does it allow all Python expressions. The operators are limited to the85most common ones and more advanced expressions such as list comprehensions86and generator expressions are not supported. This keeps the template engine87easier to maintain and templates more readable.54Some amount of logic is required in templates to keep everyone happy.55Too much logic in the template can make it complex to reason about and56maintain. It's up to you to decide how your application will work and57balance how much logic you want to put in the template.5889Why is Autoescaping not the Default?90------------------------------------5992There are multiple reasons why automatic escaping is not the default mode93and also not the recommended one. While automatic escaping of variables94means that you will less likely have an XSS problem it also causes a huge95amount of extra processing in the template engine which can cause serious96performance problems. As Python doesn't provide a way to mark strings as97unsafe Jinja has to hack around that limitation by providing a custom98string class (the :class:`~markupsafe.Markup` string) that safely interacts with safe99and unsafe strings.100101With explicit escaping however the template engine doesn't have to perform102any safety checks on variables. Also a human knows not to escape integers103or strings that may never contain characters one has to escape or already104HTML markup. For example when iterating over a list over a table of105integers and floats for a table of statistics the template designer can106omit the escaping because he knows that integers or floats don't contain107any unsafe parameters.108109Additionally Jinja is a general purpose template engine and not only used110for HTML/XML generation. For example you may generate LaTeX, emails,111CSS, JavaScript, or configuration files.112113Why is the Context immutable?114-----------------------------115116When writing a :func:`pass_context` function, you may have noticed that117the context tries to stop you from modifying it. If you have managed to118modify the context by using an internal context API you may have noticed119that changes in the context don't seem to be visible in the template.120The reason for this is that Jinja uses the context only as primary data121source for template variables for performance reasons.122123If you want to modify the context write a function that returns a variable124instead that one can assign to a variable by using set::125126 {% set comments = get_latest_comments() %}127128129My Macros are overridden by something60Why is HTML escaping not the default?61-------------------------------------62132In some situations the Jinja scoping appears arbitrary:63Jinja provides a feature that can be enabled to escape HTML syntax in64rendered templates. However, it is disabled by default.65134layout.tmpl:66Jinja is a general purpose template engine, it is not only used for HTML67documents. You can generate plain text, LaTeX, emails, CSS, JavaScript,68configuration files, etc. HTML escaping wouldn't make sense for any of69these document types.70136.. sourcecode:: jinja137138 {% macro foo() %}LAYOUT{% endmacro %}139 {% block body %}{% endblock %}140141child.tmpl:142143.. sourcecode:: jinja144145 {% extends 'layout.tmpl' %}146 {% macro foo() %}CHILD{% endmacro %}147 {% block body %}{{ foo() }}{% endblock %}148149This will print ``LAYOUT`` in Jinja. This is a side effect of having150the parent template evaluated after the child one. This allows child151templates passing information to the parent template. To avoid this152issue rename the macro or variable in the parent template to have an153uncommon prefix.154155.. _Jinja 1: https://pypi.org/project/Jinja/71While automatic escaping means that you are less likely have an XSS72problem, it also requires significant extra processing during compiling73and rendering, which can reduce performance. Jinja uses MarkupSafe for74escaping, which provides optimized C code for speed, but it still75introduces overhead to track escaping across methods and formatting.
modified:docs/integration.rst+19 added
1Integration2===========345Flask6-----78The `Flask`_ web application framework, also maintained by Pallets, uses9Jinja templates by default. Flask sets up a Jinja environment and10template loader for you, and provides functions to easily render11templates from view functions.1213.. _Flask: https://flask.palletsprojects.com141516Django17------1819Django supports using Jinja as its template engine, see20https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines.212223.. _babel-integration:2425Babel26-----
68 unmodified lines
modified:docs/switching.rst+78 added-123 removed
1Switching from other Template Engines1Switching From Other Template Engines2=====================================34.. highlight:: html+jinja4This is a brief guide on some of the differences between Jinja syntax5and other template languages. See :doc:`/templates` for a comprehensive6guide to Jinja syntax and features.76If you have used a different template engine in the past and want to switch7to Jinja here is a small guide that shows the basic syntactic and semantic8changes between some common, similar text template engines for Python.810Jinja 111-------1213Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template14syntax. The differences between Jinja 1 and 2 are explained in the following15list.1617API18~~~1920Loaders21 Jinja 2 uses a different loader API. Because the internal representation22 of templates changed there is no longer support for external caching23 systems such as memcached. The memory consumed by templates is comparable24 with regular Python modules now and external caching doesn't give any25 advantage. If you have used a custom loader in the past have a look at26 the new :ref:`loader API <loaders>`.2728Loading templates from strings29 In the past it was possible to generate templates from a string with the30 default environment configuration by using `jinja.from_string`. Jinja 231 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.3334Automatic unicode conversion35 Jinja 1 performed automatic conversion of bytes in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python38 ASCII bytes to Unicode conversion. An application powered by Jinja 239 *has to* use unicode internally everywhere or make sure that Jinja 240 only gets unicode strings passed.4142i18n43 Jinja 1 used custom translators for internationalization. i18n is now44 available as Jinja 2 extension and uses a simpler, more gettext friendly45 interface and has support for babel. For more details see46 :ref:`i18n-extension`.4748Internal methods49 Jinja 1 exposed a few internal methods on the environment object such50 as `call_function`, `get_attribute` and others. While they were marked51 as being an internal method it was possible to override them. Jinja 252 doesn't have equivalent methods.5354Sandbox55 Jinja 1 was running sandbox mode by default. Few applications actually56 used that feature so it became optional in Jinja 2. For more details57 about the sandboxed execution see :class:`SandboxedEnvironment`.5859Context60 Jinja 1 had a stacked context as storage for variables passed to the61 environment. In Jinja 2 a similar object exists but it doesn't allow62 modifications nor is it a singleton. As inheritance is dynamic now63 multiple context objects may exist during template evaluation.6465Filters and Tests66 Filters and tests are regular functions now. It's no longer necessary67 and allowed to use factory functions.686970Templates71~~~~~~~~~7273Jinja 2 has mostly the same syntax as Jinja 1. What's different is that74macros require parentheses around the argument list now.7576Additionally Jinja 2 allows dynamic inheritance now and dynamic includes.77The old helper function `rendertemplate` is gone now, `include` can be used78instead. Includes no longer import macros and variable assignments, for79that the new `import` tag is used. This concept is explained in the80:ref:`import` documentation.8182Another small change happened in the `for`-tag. The special loop variable83doesn't have a `parent` attribute, instead you have to alias the loop84yourself. See :ref:`accessing-the-parent-loop` for more details.85869Django10------1112If you have previously worked with Django templates, you should find91Jinja very familiar. In fact, most of the syntax elements look and92work the same.13Jinja very familiar. Many of the syntax elements look and work the same.14However, Jinja provides some more syntax elements, and some work a bit15differently.1694However, Jinja provides some more syntax elements covered in the95documentation and some work a bit different.17This section covers the template changes. The API, including extension18support, is fundamentally different so it won't be covered here.1997This section covers the template changes. As the API is fundamentally98different we won't cover it here.20Django supports using Jinja as its template engine, see21https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines.222324Method Calls25~~~~~~~~~~~~26103In Django method calls work implicitly, while Jinja requires the explicit104Python syntax. Thus this Django code::27In Django, methods are called implicitly, without parentheses.2829.. code-block:: django3031 {% for page in user.get_created_pages %}32 ...33 {% endfor %}34110...looks like this in Jinja::35In Jinja, using parentheses is required for calls, like in Python. This36allows you to pass variables to the method, which is not possible37in Django. This syntax is also used for calling macros.3839.. code-block:: jinja4041 {% for page in user.get_created_pages() %}42 ...43 {% endfor %}44116This allows you to pass variables to the method, which is not possible in117Django. This syntax is also used for macros.4546Filter Arguments47~~~~~~~~~~~~~~~~48122Jinja provides more than one argument for filters. Also the syntax for123argument passing is different. A template that looks like this in Django::49In Django, one literal value can be passed to a filter after a colon.5051.. code-block:: django5253 {{ items|join:", " }}54127looks like this in Jinja::55In Jinja, filters can take any number of positional and keyword56arguments in parentheses, like function calls. Arguments can also be57variables instead of literal values.58129 {{ items|join(', ') }}59.. code-block:: jinja60131It is a bit more verbose, but it allows different types of arguments -132including variables - and more than one of them.61 {{ items|join(", ") }}626364Tests65~~~~~66137In addition to filters there also are tests you can perform using the is138operator. Here are some examples::67In addition to filters, Jinja also has "tests" used with the ``is``68operator. This operator is not the same as the Python operator.6970.. code-block:: jinja7172 {% if user.user_id is odd %}73 {{ user.username|e }} is odd74 {% else %}75 hmm. {{ user.username|e }} looks pretty normal
1 unmodified line
7778Loops79~~~~~80149For loops work very similarly to Django, but notably the Jinja special150variable for the loop context is called `loop`, not `forloop` as in Django.81In Django, the special variable for the loop context is called82``forloop``, and the ``empty`` is used for no loop items.83152In addition, the Django `empty` argument is called `else` in Jinja. For153example, the Django template::84.. code-block:: django8586 {% for item in items %}87 {{ item }}88 {% empty %}89 No items!90 {% endfor %}91161...looks like this in Jinja::92In Jinja, the special variable for the loop context is called ``loop``,93and the ``else`` block is used for no loop items.9495.. code-block:: jinja9697 {% for item in items %}164 {{ item }}98 {{ loop.index}}. {{ item }}99 {% else %}100 No items!101 {% endfor %}102103104Cycle105~~~~~106172The ``{% cycle %}`` tag does not exist in Jinja; however, you can achieve the173same output by using the `cycle` method on the loop context special variable.107In Django, the ``{% cycle %}`` can be used in a for loop to alternate108between values per loop.109175The following Django template::110.. code-block:: django111112 {% for user in users %}113 <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>114 {% endfor %}115181...looks like this in Jinja::116In Jinja, the ``loop`` context has a ``cycle`` method.117118.. code-block:: jinja119120 {% for user in users %}121 <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>122 {% endfor %}123187There is no equivalent of ``{% cycle ... as variable %}``.124A cycler can also be assigned to a variable and used outside or across125loops with the ``cycle()`` global function.126127128Mako129----130193.. highlight:: html+mako131You can configure Jinja to look more like Mako:132195If you have used Mako so far and want to switch to Jinja you can configure196Jinja to look more like Mako:133.. code-block:: python134198.. sourcecode:: python135 env = Environment(136 block_start_string="<%",137 block_end_string="%>",138 variable_start_string="${",139 variable_end_string="}",140 comment_start_string="<%doc>",141 commend_end_string="</%doc>",142 line_statement_prefix="%",143 line_comment_prefix="##",144 )145200 env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')146With an environment configured like that, Jinja should be able to147interpret a small subset of Mako templates without any changes.148202With an environment configured like that, Jinja should be able to interpret203a small subset of Mako templates. Jinja does not support embedded Python204code, so you would have to move that out of the template. The syntax for defs205(which are called macros in Jinja) and template inheritance is different too.206The following Mako template::149Jinja does not support embedded Python code, so you would have to move150that out of the template. You could either process the data with the151same code before rendering, or add a global function or filter to the152Jinja environment.153154The syntax for defs (which are called macros in Jinja) and template155inheritance is different too.156157The following Mako template:158159.. code-block:: mako160161 <%inherit file="layout.html" />162 <%def name="title()">Page Title</%def>163 <ul>164 % for item in list:165 <li>${item}</li>166 % endfor167 </ul>168216Looks like this in Jinja with the above configuration::169Looks like this in Jinja with the above configuration:170171.. code-block:: jinja172173 <% extends "layout.html" %>174 <% block title %>Page Title<% endblock %>175 <% block body %>176 <ul>
5 unmodified lines
modified:docs/templates.rst+41 added-21 removed
936 unmodified lines
937938If a macro name starts with an underscore, it's not exported and can't939be imported.940941Due to how scopes work in Jinja, a macro in a child template does not942override a macro in a parent template. The following will output943"LAYOUT", not "CHILD".944945.. code-block:: jinja946 :caption: ``layout.txt``947948 {% macro foo() %}LAYOUT{% endmacro %}949 {% block body %}{% endblock %}950951.. code-block:: jinja952 :caption: ``child.txt``953954 {% extends 'layout.txt' %}955 {% macro foo() %}CHILD{% endmacro %}956 {% block body %}{{ foo() }}{% endblock %}957958959.. _call:960961Call962~~~~
166 unmodified lines
11291130Include1131~~~~~~~11321116The `include` tag is useful to include a template and return the1117rendered contents of that file into the current namespace::1133The ``include`` tag renders another template and outputs the result into1134the current template.11351136.. code-block:: jinja11371138 {% include 'header.html' %}1120 Body1139 Body goes here.1140 {% include 'footer.html' %}11411123Included templates have access to the variables of the active context by1124default. For more details about context behavior of imports and includes,1125see :ref:`import-visibility`.1142The included template has access to context of the current template by1143default. Use ``without context`` to use a separate context instead.1144``with context`` is also valid, but is the default behavior. See1145:ref:`import-visibility`.11461127From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in1128which case Jinja will ignore the statement if the template to be included1129does not exist. When combined with ``with`` or ``without context``, it must1130be placed *before* the context visibility statement. Here are some valid1131examples::1147The included template can ``extend`` another template and override1148blocks in that template. However, the current template cannot override1149any blocks that the included template outputs.11501151Use ``ignore missing`` to ignore the statement if the template does not1152exist. It must be placed *before* a context visibility statement.11531154.. code-block:: jinja11551156 {% include "sidebar.html" without context %}1157 {% include "sidebar.html" ignore missing %}1158 {% include "sidebar.html" ignore missing with context %}1159 {% include "sidebar.html" ignore missing without context %}11601137.. versionadded:: 2.21161If a list of templates is given, each will be tried in order until one1162is not missing. This can be used with ``ignore missing`` to ignore if1163none of the templates exist.11641139You can also provide a list of templates that are checked for existence1140before inclusion. The first template that exists will be included. If1141`ignore missing` is given, it will fall back to rendering nothing if1142none of the templates exist, otherwise it will raise an exception.1165.. code-block:: jinja11661144Example::11451167 {% include ['page_detailed.html', 'page.html'] %}1168 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}11691149.. versionchanged:: 2.41150 If a template object was passed to the template context, you can1151 include that object using `include`.1170A variable, with either a template name or template object, can also be1171passed to the statment.11721173.. _import:11741175Import
774 unmodified lines