Skip to content
Myr

clean up faq, move technical discussions

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

authored by David Lord · committed by David Lord · parent 9de99f8 · Browse files · 3 files+78 added−138 removed
This commit

State

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

Diff stats

3 files+78 added−138 removed

  • other:+78 added−138 removed

3 files+78 added−138 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/templates.rst+17 added
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~~~~
984 unmodified lines