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
Provenance
- Commit
3a050b1- Tree
87c8c1d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
350bc53- Parent 2
4b63cd8
5 files changed+199 added−282 removed
modified:docs/api.rst+11 added-8 removed
408 unmodified lines409 410 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)411 412 413-.. admonition:: Implementation413+The context is immutable, it prevents modifications, and if it is414+modified somehow despite that those changes may not show up. For415+performance, Jinja does not use the context as data storage for, only as416+a primary data source. Variables that the template does not define are417+looked up in the context, but variables the template does define are418+stored locally.419 415- 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.420+Instead of modifying the context directly, a function should return421+a value that can be assigned to a variable within the template itself.422 420- 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:: jinja424 425+ {% set comments = get_latest_comments() %}426 427+428 .. _loaders:429 430 Loaders431 -------491 unmodified linesmodified:docs/faq.rst+50 added-130 removed
1 Frequently Asked Questions2 ==========================3 4-This page answers some of the often asked questions about Jinja.4 6-.. highlight:: html+jinja7-5 Why is it called Jinja?6 -----------------------7 11-The name Jinja was chosen because it's the name of a Japanese temple and12-temple and template share a similar pronunciation. It is not named after13-the city in Uganda.8+"Jinja" is a Japanese `Shinto shrine`_, or temple, and temple and9+template share a similar English pronunciation. It is not named after10+the `city in Uganda`_.11 15-How fast is it?16----------------12+.. _Shinto shrine: https://en.wikipedia.org/wiki/Shinto_shrine13+.. _city in Uganda: https://en.wikipedia.org/wiki/Jinja%2C_Uganda14 18-We really hate benchmarks especially since they don't reflect much. The19-performance of a template depends on many factors and you would have to20-benchmark different engines in different situations. The benchmarks from the21-testsuite show that Jinja has a similar performance to `Mako`_ and is between22-10 and 20 times faster than Django's template engine or Genshi. These numbers23-should be taken with tons of salt as the benchmarks that took these numbers24-only test a few performance related situations such as looping. Generally25-speaking the performance of a template engine doesn't matter much as the26-usual bottleneck in a web application is either the database or the application27-code.15 29-.. _Mako: https://www.makotemplates.org/16+How fast is Jinja?17+------------------18 31-How Compatible is Jinja with Django?32-------------------------------------19+Jinja is relatively fast among template engines because it compiles and20+caches template code to Python code, so that the template does not need21+to be parsed and interpreted each time. Rendering a template becomes as22+close to executing a Python function as possible.23 34-The default syntax of Jinja matches Django syntax in many ways. However35-this similarity doesn't mean that you can use a Django template unmodified36-in Jinja. For example filter arguments use a function call syntax rather37-than a colon to separate filter name and arguments. Additionally the38-extension interface in Jinja is fundamentally different from the Django one39-which means that your custom tags won't work any longer.24+Jinja also makes extensive use of caching. Templates are cached by name25+after loading, so future uses of the template avoid loading. The26+template loading itself uses a bytecode cache to avoid repeated27+compiling. The caches can be external to persist across restarts.28+Templates can also be precompiled and loaded as fast Python imports.29 41-Generally speaking you will use much less custom extensions as the Jinja42-template system allows you to use a certain subset of Python expressions43-which can replace most Django extensions. For example instead of using44-something like this::30+We dislike benchmarks because they don't reflect real use. Performance31+depends on many factors. Different engines have different default32+configurations and tradeoffs that make it unclear how to set up a useful33+comparison. Often, database access, API calls, and data processing have34+a much larger effect on performance than the template engine.35 46- {% load comments %}47- {% get_latest_comments 10 as latest_comments %}48- {% for comment in latest_comments %}49- ...50- {% endfor %}36 52-You will most likely provide an object with attributes to retrieve53-comments from the database::37+Isn't it a bad idea to put logic in templates?38+----------------------------------------------39 55- {% for comment in models.comments.latest(10) %}56- ...57- {% endfor %}58-59-Or directly provide the model for quick testing::60-61- {% for comment in Comment.objects.order_by('-pub_date')[:10] %}62- ...63- {% endfor %}64-65-Please keep in mind that even though you may put such things into templates66-it still isn't a good idea. Queries should go into the view code and not67-the template!68-69-Isn't it a terrible idea to put Logic into Templates?70------------------------------------------------------71-40 Without a doubt you should try to remove as much logic from templates as73-possible. But templates without any logic mean that you have to do all74-the processing in the code which is boring and stupid. A template engine75-that does that is shipped with Python and called `string.Template`. Comes76-without loops and if conditions and is by far the fastest template engine77-you can get for Python.41+possible. With less logic, the template is easier to understand, has42+fewer potential side effects, and is faster to compile and render. But a43+template without any logic means processing must be done in code before44+rendering. A template engine that does that is shipped with Python,45+called :class:`string.Template`, and while it's definitely fast it's not46+convenient.47 79-So some amount of logic is required in templates to keep everyone happy.80-And Jinja leaves it pretty much to you how much logic you want to put into81-templates. There are some restrictions in what you can do and what not.48+Jinja's features such as blocks, statements, filters, and function calls49+make it much easier to write expressive templates, with very few50+restrictions. Jinja doesn't allow arbitrary Python code in templates, or51+every feature available in the Python language. This keeps the engine52+easier to maintain, and keeps templates more readable.53 83-Jinja neither allows you to put arbitrary Python code into templates nor84-does it allow all Python expressions. The operators are limited to the85-most common ones and more advanced expressions such as list comprehensions86-and generator expressions are not supported. This keeps the template engine87-easier to maintain and templates more readable.54+Some amount of logic is required in templates to keep everyone happy.55+Too much logic in the template can make it complex to reason about and56+maintain. It's up to you to decide how your application will work and57+balance how much logic you want to put in the template.58 89-Why is Autoescaping not the Default?90-------------------------------------59 92-There are multiple reasons why automatic escaping is not the default mode93-and also not the recommended one. While automatic escaping of variables94-means that you will less likely have an XSS problem it also causes a huge95-amount of extra processing in the template engine which can cause serious96-performance problems. As Python doesn't provide a way to mark strings as97-unsafe Jinja has to hack around that limitation by providing a custom98-string class (the :class:`~markupsafe.Markup` string) that safely interacts with safe99-and unsafe strings.100-101-With explicit escaping however the template engine doesn't have to perform102-any safety checks on variables. Also a human knows not to escape integers103-or strings that may never contain characters one has to escape or already104-HTML markup. For example when iterating over a list over a table of105-integers and floats for a table of statistics the template designer can106-omit the escaping because he knows that integers or floats don't contain107-any unsafe parameters.108-109-Additionally Jinja is a general purpose template engine and not only used110-for HTML/XML generation. For example you may generate LaTeX, emails,111-CSS, JavaScript, or configuration files.112-113-Why is the Context immutable?114------------------------------115-116-When writing a :func:`pass_context` function, you may have noticed that117-the context tries to stop you from modifying it. If you have managed to118-modify the context by using an internal context API you may have noticed119-that changes in the context don't seem to be visible in the template.120-The reason for this is that Jinja uses the context only as primary data121-source for template variables for performance reasons.122-123-If you want to modify the context write a function that returns a variable124-instead that one can assign to a variable by using set::125-126- {% set comments = get_latest_comments() %}127-128-129-My Macros are overridden by something60+Why is HTML escaping not the default?61 -------------------------------------62 132-In some situations the Jinja scoping appears arbitrary:63+Jinja provides a feature that can be enabled to escape HTML syntax in64+rendered templates. However, it is disabled by default.65 134-layout.tmpl:66+Jinja is a general purpose template engine, it is not only used for HTML67+documents. You can generate plain text, LaTeX, emails, CSS, JavaScript,68+configuration files, etc. HTML escaping wouldn't make sense for any of69+these document types.70 136-.. sourcecode:: jinja137-138- {% macro foo() %}LAYOUT{% endmacro %}139- {% block body %}{% endblock %}140-141-child.tmpl:142-143-.. sourcecode:: jinja144-145- {% extends 'layout.tmpl' %}146- {% macro foo() %}CHILD{% endmacro %}147- {% block body %}{{ foo() }}{% endblock %}148-149-This will print ``LAYOUT`` in Jinja. This is a side effect of having150-the parent template evaluated after the child one. This allows child151-templates passing information to the parent template. To avoid this152-issue rename the macro or variable in the parent template to have an153-uncommon prefix.154-155-.. _Jinja 1: https://pypi.org/project/Jinja/71+While automatic escaping means that you are less likely have an XSS72+problem, it also requires significant extra processing during compiling73+and rendering, which can reduce performance. Jinja uses MarkupSafe for74+escaping, which provides optimized C code for speed, but it still75+introduces overhead to track escaping across methods and formatting.modified:docs/integration.rst+19 added
1 Integration2 ===========3 4+5+Flask6+-----7+8+The `Flask`_ web application framework, also maintained by Pallets, uses9+Jinja templates by default. Flask sets up a Jinja environment and10+template loader for you, and provides functions to easily render11+templates from view functions.12+13+.. _Flask: https://flask.palletsprojects.com14+15+16+Django17+------18+19+Django supports using Jinja as its template engine, see20+https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines.21+22+23 .. _babel-integration:24 25 Babel26 -----68 unmodified linesmodified:docs/switching.rst+78 added-123 removed
1-Switching from other Template Engines1+Switching From Other Template Engines2 =====================================3 4-.. highlight:: html+jinja4+This is a brief guide on some of the differences between Jinja syntax5+and other template languages. See :doc:`/templates` for a comprehensive6+guide to Jinja syntax and features.7 6-If you have used a different template engine in the past and want to switch7-to Jinja here is a small guide that shows the basic syntactic and semantic8-changes between some common, similar text template engines for Python.8 10-Jinja 111--------12-13-Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template14-syntax. The differences between Jinja 1 and 2 are explained in the following15-list.16-17-API18-~~~19-20-Loaders21- Jinja 2 uses a different loader API. Because the internal representation22- of templates changed there is no longer support for external caching23- systems such as memcached. The memory consumed by templates is comparable24- with regular Python modules now and external caching doesn't give any25- advantage. If you have used a custom loader in the past have a look at26- the new :ref:`loader API <loaders>`.27-28-Loading templates from strings29- In the past it was possible to generate templates from a string with the30- default environment configuration by using `jinja.from_string`. Jinja 231- provides a :class:`Template` class that can be used to do the same, but32- with optional additional configuration.33-34-Automatic unicode conversion35- 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.41-42-i18n43- Jinja 1 used custom translators for internationalization. i18n is now44- available as Jinja 2 extension and uses a simpler, more gettext friendly45- interface and has support for babel. For more details see46- :ref:`i18n-extension`.47-48-Internal methods49- 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.53-54-Sandbox55- Jinja 1 was running sandbox mode by default. Few applications actually56- used that feature so it became optional in Jinja 2. For more details57- about the sandboxed execution see :class:`SandboxedEnvironment`.58-59-Context60- Jinja 1 had a stacked context as storage for variables passed to the61- environment. In Jinja 2 a similar object exists but it doesn't allow62- modifications nor is it a singleton. As inheritance is dynamic now63- multiple context objects may exist during template evaluation.64-65-Filters and Tests66- Filters and tests are regular functions now. It's no longer necessary67- and allowed to use factory functions.68-69-70-Templates71-~~~~~~~~~72-73-Jinja 2 has mostly the same syntax as Jinja 1. What's different is that74-macros require parentheses around the argument list now.75-76-Additionally Jinja 2 allows dynamic inheritance now and dynamic includes.77-The old helper function `rendertemplate` is gone now, `include` can be used78-instead. Includes no longer import macros and variable assignments, for79-that the new `import` tag is used. This concept is explained in the80-:ref:`import` documentation.81-82-Another small change happened in the `for`-tag. The special loop variable83-doesn't have a `parent` attribute, instead you have to alias the loop84-yourself. See :ref:`accessing-the-parent-loop` for more details.85-86-9 Django10 ------11 12 If you have previously worked with Django templates, you should find91-Jinja very familiar. In fact, most of the syntax elements look and92-work the same.13+Jinja very familiar. Many of the syntax elements look and work the same.14+However, Jinja provides some more syntax elements, and some work a bit15+differently.16 94-However, Jinja provides some more syntax elements covered in the95-documentation and some work a bit different.17+This section covers the template changes. The API, including extension18+support, is fundamentally different so it won't be covered here.19 97-This section covers the template changes. As the API is fundamentally98-different we won't cover it here.20+Django supports using Jinja as its template engine, see21+https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines.22 23+24 Method Calls25 ~~~~~~~~~~~~26 103-In Django method calls work implicitly, while Jinja requires the explicit104-Python syntax. Thus this Django code::27+In Django, methods are called implicitly, without parentheses.28 29+.. code-block:: django30+31 {% for page in user.get_created_pages %}32 ...33 {% endfor %}34 110-...looks like this in Jinja::35+In Jinja, using parentheses is required for calls, like in Python. This36+allows you to pass variables to the method, which is not possible37+in Django. This syntax is also used for calling macros.38 39+.. code-block:: jinja40+41 {% for page in user.get_created_pages() %}42 ...43 {% endfor %}44 116-This allows you to pass variables to the method, which is not possible in117-Django. This syntax is also used for macros.45 46 Filter Arguments47 ~~~~~~~~~~~~~~~~48 122-Jinja provides more than one argument for filters. Also the syntax for123-argument passing is different. A template that looks like this in Django::49+In Django, one literal value can be passed to a filter after a colon.50 51+.. code-block:: django52+53 {{ items|join:", " }}54 127-looks like this in Jinja::55+In Jinja, filters can take any number of positional and keyword56+arguments in parentheses, like function calls. Arguments can also be57+variables instead of literal values.58 129- {{ items|join(', ') }}59+.. code-block:: jinja60 131-It is a bit more verbose, but it allows different types of arguments -132-including variables - and more than one of them.61+ {{ items|join(", ") }}62 63+64 Tests65 ~~~~~66 137-In addition to filters there also are tests you can perform using the is138-operator. Here are some examples::67+In addition to filters, Jinja also has "tests" used with the ``is``68+operator. This operator is not the same as the Python operator.69 70+.. code-block:: jinja71+72 {% if user.user_id is odd %}73 {{ user.username|e }} is odd74 {% else %}75 hmm. {{ user.username|e }} looks pretty normal1 unmodified line77 78 Loops79 ~~~~~80 149-For loops work very similarly to Django, but notably the Jinja special150-variable for the loop context is called `loop`, not `forloop` as in Django.81+In Django, the special variable for the loop context is called82+``forloop``, and the ``empty`` is used for no loop items.83 152-In addition, the Django `empty` argument is called `else` in Jinja. For153-example, the Django template::84+.. code-block:: django85 86 {% for item in items %}87 {{ item }}88 {% empty %}89 No items!90 {% endfor %}91 161-...looks like this in Jinja::92+In Jinja, the special variable for the loop context is called ``loop``,93+and the ``else`` block is used for no loop items.94 95+.. code-block:: jinja96+97 {% for item in items %}164- {{ item }}98+ {{ loop.index}}. {{ item }}99 {% else %}100 No items!101 {% endfor %}102 103+104 Cycle105 ~~~~~106 172-The ``{% cycle %}`` tag does not exist in Jinja; however, you can achieve the173-same output by using the `cycle` method on the loop context special variable.107+In Django, the ``{% cycle %}`` can be used in a for loop to alternate108+between values per loop.109 175-The following Django template::110+.. code-block:: django111 112 {% for user in users %}113 <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>114 {% endfor %}115 181-...looks like this in Jinja::116+In Jinja, the ``loop`` context has a ``cycle`` method.117 118+.. code-block:: jinja119+120 {% for user in users %}121 <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>122 {% endfor %}123 187-There is no equivalent of ``{% cycle ... as variable %}``.124+A cycler can also be assigned to a variable and used outside or across125+loops with the ``cycle()`` global function.126 127 128 Mako129 ----130 193-.. highlight:: html+mako131+You can configure Jinja to look more like Mako:132 195-If you have used Mako so far and want to switch to Jinja you can configure196-Jinja to look more like Mako:133+.. code-block:: python134 198-.. 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+ )145 200- env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')146+With an environment configured like that, Jinja should be able to147+interpret a small subset of Mako templates without any changes.148 202-With an environment configured like that, Jinja should be able to interpret203-a small subset of Mako templates. Jinja does not support embedded Python204-code, so you would have to move that out of the template. The syntax for defs205-(which are called macros in Jinja) and template inheritance is different too.206-The following Mako template::149+Jinja does not support embedded Python code, so you would have to move150+that out of the template. You could either process the data with the151+same code before rendering, or add a global function or filter to the152+Jinja environment.153 154+The syntax for defs (which are called macros in Jinja) and template155+inheritance is different too.156+157+The following Mako template:158+159+.. code-block:: mako160+161 <%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>168 216-Looks like this in Jinja with the above configuration::169+Looks like this in Jinja with the above configuration:170 171+.. code-block:: jinja172+173 <% extends "layout.html" %>174 <% block title %>Page Title<% endblock %>175 <% block body %>176 <ul>5 unmodified linesmodified:docs/templates.rst+41 added-21 removed
936 unmodified lines937 938 If a macro name starts with an underscore, it's not exported and can't939 be imported.940 941+Due to how scopes work in Jinja, a macro in a child template does not942+override a macro in a parent template. The following will output943+"LAYOUT", not "CHILD".944 945+.. code-block:: jinja946+ :caption: ``layout.txt``947+948+ {% macro foo() %}LAYOUT{% endmacro %}949+ {% block body %}{% endblock %}950+951+.. code-block:: jinja952+ :caption: ``child.txt``953+954+ {% extends 'layout.txt' %}955+ {% macro foo() %}CHILD{% endmacro %}956+ {% block body %}{{ foo() }}{% endblock %}957+958+959 .. _call:960 961 Call962 ~~~~166 unmodified lines1129 1130 Include1131 ~~~~~~~1132 1116-The `include` tag is useful to include a template and return the1117-rendered contents of that file into the current namespace::1133+The ``include`` tag renders another template and outputs the result into1134+the current template.1135 1136+.. code-block:: jinja1137+1138 {% include 'header.html' %}1120- Body1139+ Body goes here.1140 {% include 'footer.html' %}1141 1123-Included templates have access to the variables of the active context by1124-default. For more details about context behavior of imports and includes,1125-see :ref:`import-visibility`.1142+The included template has access to context of the current template by1143+default. Use ``without context`` to use a separate context instead.1144+``with context`` is also valid, but is the default behavior. See1145+:ref:`import-visibility`.1146 1127-From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in1128-which case Jinja will ignore the statement if the template to be included1129-does not exist. When combined with ``with`` or ``without context``, it must1130-be placed *before* the context visibility statement. Here are some valid1131-examples::1147+The included template can ``extend`` another template and override1148+blocks in that template. However, the current template cannot override1149+any blocks that the included template outputs.1150 1151+Use ``ignore missing`` to ignore the statement if the template does not1152+exist. It must be placed *before* a context visibility statement.1153+1154+.. code-block:: jinja1155+1156+ {% 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 %}1160 1137-.. versionadded:: 2.21161+If a list of templates is given, each will be tried in order until one1162+is not missing. This can be used with ``ignore missing`` to ignore if1163+none of the templates exist.1164 1139-You can also provide a list of templates that are checked for existence1140-before inclusion. The first template that exists will be included. If1141-`ignore missing` is given, it will fall back to rendering nothing if1142-none of the templates exist, otherwise it will raise an exception.1165+.. code-block:: jinja1166 1144-Example::1145-1167 {% include ['page_detailed.html', 'page.html'] %}1168 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}1169 1149-.. versionchanged:: 2.41150- If a template object was passed to the template context, you can1151- include that object using `include`.1170+A variable, with either a template name or template object, can also be1171+passed to the statment.1172 1173 .. _import:1174 1175 Import774 unmodified lines