Skip to content
Myr

[svn] splitted jinja documentation into more files

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

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 44fb2e1 · Browse files · 8 files+690 added−649 removed
This commit

State

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

Diff stats

8 files+690 added−649 removed

  • other:+690 added−649 removed

8 files+690 added−649 removed

added:docs/src/builtins.txt+203 added
1===================================2Filters, Tests and Helper Functions3===================================45This part of the documentation lists the filter-, test- and helper functions6you can use in templates.789Filters10=======1112In the examples above you might have noticed the pipe symbols. Pipe symbols tell13the engine that it has to apply a filter on the variable. Here is a small example:1415.. sourcecode:: jinja1617 {{ variable|replace('foo', 'bar')|escape }}1819If you want, you can also put whitespace between the filters.2021This will look for a variable `variable`, pass it to the filter `replace`22with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter23`escape` that automatically XML-escapes the value. The `e` filter is an alias for24`escape`. Here is the complete list of supported filters:2526[[list_of_filters]]2728.. admonition:: note2930 The filter operator has a pretty low priority. If you want to add fitered31 values you have to put them into parentheses. The same applies if you want32 to access attributes or return values:3334 .. sourcecode:: jinja3536 correct:37 {{ (foo|filter) + (bar|filter) }}38 wrong:39 {{ foo|filter + bar|filter }}4041 correct:42 {{ (foo|filter).attribute }}43 wrong:44 {{ foo|filter.attribute }}4546*new in Jinja 1.1*:4748Because the application can provide additional filters you can get a documentation49of all the provided filters by calling ``debug.filters()``:5051.. sourcecode:: jinja5253 {{ debug.filters() }}54 -> returns a plain text representation of all the filters5556 {{ debug.filters(False) }}57 -> same as above but without the builtin ones.5859Tests60=====6162You can use the `is` operator to perform tests on a value:6364.. sourcecode:: jinja6566 {{ 42 is numeric }} -> true67 {{ "foobar" is numeric }} -> false68 {{ 'FOO' is upper }} -> true6970These tests are especially useful when used in `if` conditions.7172[[list_of_tests]]7374*new in Jinja 1.1*:7576Because the application can provide additional tests you can get a documentation77of all the provided tests by calling ``debug.tests()``:7879.. sourcecode:: jinja8081 {{ debug.tests() }}82 -> returns a plain text representation of all the tests8384 {{ debug.tests(False) }}85 -> same as above but without the builtin ones.868788Global Functions89================9091Test functions and filter functions live in their own namespace. Global92functions not. They behave like normal objects in the context. Beside the93functions added by the application or framewhere there are two functions94available per default:9596`range`97 98 Works like the python `range function`_ just that it doesn't support99 ranges greater than ``1000000``.100101`debug`102103 Function that outputs the contents of the context.104105`lipsum`106107 Generate some paragraphs of random text:108109 .. sourcecode:: jinja110111 {{ lipsum(5) }}112 five html paragraphs113114 {{ lipsum(2, False) }}115 two ascii only paragraphs116117 Per default a paragraph is between 20 and 100 words long. You can118 override this default with the third and fourth parameter:119120 .. sourcecode:: jinja121122 {{ lipsum(10, True, 50, 200) }}123 generate 10 HTML paragraphs between 50 and 200 words.124125 *new in Jinja 1.1*126127`watchchanges`128129 Jinja does not provide an django like ``{% ifchanged %}`` tag. As130 replacement for this tag there is a special function in the namespace131 called `watchchanges`.132133 You can use it like this:134135 .. sourcecode:: html+jinja136137 {% for changed, article in watchchanges(articles, 'date', 'day') %}138 {% if changed %}<h3>{{ articles.date.day }}</h3>{% endif %}139 <h4>{{ article.title|e }}</h4>140 <p>{{ article.body|e }}</p>141 {% endif %}142143 For each iteration `watchchanges` will check the given attribute. If it144 changed to the former iteration the first yielded item (in this example145 it's called `changed`) will be `true`, else `false`.146147 In this example `articles` is a list of articles for the template with148 an attribute called `date.day` which represents the current day. To only149 add a new day headline if the day has changed `watchchanges` is now told150 to check `articles.date.days`.151152 If you want to observe more than one attribute you can provide pairs:153154 .. sourcecode:: html+jinja155156 {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}157 ...158 {% endfor %}159160 Note that if you want to watch two first level attributes you have to161 either use the list syntax `[]` or add a colon:162163 .. sourcecode:: html+jinja164165 {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}166 ...167 {% endfor %}168169 otherwise Jinja cannot differ between a pair of parentheses to group170 expressions or the sequence syntax.171172 If you don't provide any arguments the value of the variable itself173 is checked.174175 *new in Jinja 1.1*176177178Global Constants179================180181Jinja provides some special variables which cannot be overridden in templates.182Those are not affected by the variable lookup:183184 `_`, `true`, `false`, `none`, `undefined`185186You cannot use those names for your own variables or macros. It's however no187problem to have blocks with that name.188189**Notice** due to a bug in Jinja 1.0 it was possible to override `_`, `true`,190`false`, `none` and `undefined` from the template by either using `{% set %}`191or in a for loop. While overriding `true`, `false` etc just caused nothing192overriding the translation marker `_` would crash the translation interface.193If you want to use `_` for unpacking in for loops (eg. skipping items) you194have to give it a proper name:195196.. sourcecode:: jinja197198 {% for key, ignore in mydict|dictsort %}199 {{ key|e }}200 {% endfor %}201202203.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000
modified:docs/src/designerdoc.txt+8 added-644 removed
65 unmodified lines
66 {{ users[current_user].username }}67 If you have numerical indices you have to use the [] syntax:68 {{ users[0].username }}6970Filters71=======7273In the examples above you might have noticed the pipe symbols. Pipe symbols tell74the engine that it has to apply a filter on the variable. Here is a small example:7576.. sourcecode:: jinja7778 {{ variable|replace('foo', 'bar')|escape }}7980If you want, you can also put whitespace between the filters.8182This will look for a variable `variable`, pass it to the filter `replace`83with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter84`escape` that automatically XML-escapes the value. The `e` filter is an alias for85`escape`. Here is the complete list of supported filters:8687[[list_of_filters]]8889.. admonition:: note9091 The filter operator has a pretty low priority. If you want to add fitered92 values you have to put them into parentheses. The same applies if you want93 to access attributes or return values:9495 .. sourcecode:: jinja9697 correct:98 {{ (foo|filter) + (bar|filter) }}99 wrong:100 {{ foo|filter + bar|filter }}101102 correct:103 {{ (foo|filter).attribute }}104 wrong:105 {{ foo|filter.attribute }}106107*new in Jinja 1.1*:108109Because the application can provide additional filters you can get a documentation110of all the provided filters by calling ``debug.filters()``:111112.. sourcecode:: jinja113114 {{ debug.filters() }}115 -> returns a plain text representation of all the filters116117 {{ debug.filters(False) }}118 -> same as above but without the builtin ones.119120Tests121=====122123You can use the `is` operator to perform tests on a value:124125.. sourcecode:: jinja126127 {{ 42 is numeric }} -> true128 {{ "foobar" is numeric }} -> false129 {{ 'FOO' is upper }} -> true130131These tests are especially useful when used in `if` conditions.132133[[list_of_tests]]134135*new in Jinja 1.1*:136137Because the application can provide additional tests you can get a documentation138of all the provided tests by calling ``debug.tests()``:139140.. sourcecode:: jinja141142 {{ debug.tests() }}143 -> returns a plain text representation of all the tests144145 {{ debug.tests(False) }}146 -> same as above but without the builtin ones.147148149Global Functions150================151152Test functions and filter functions live in their own namespace. Global153functions not. They behave like normal objects in the context. Beside the154functions added by the application or framewhere there are two functions155available per default:156157`range`158 159 Works like the python `range function`_ just that it doesn't support160 ranges greater than ``1000000``.161162`debug`163164 Function that outputs the contents of the context.165166`lipsum`167168 Generate some paragraphs of random text:169170 .. sourcecode:: jinja171172 {{ lipsum(5) }}173 five html paragraphs174175 {{ lipsum(2, False) }}176 two ascii only paragraphs177178 Per default a paragraph is between 20 and 100 words long. You can179 override this default with the third and fourth parameter:180181 .. sourcecode:: jinja182183 {{ lipsum(10, True, 50, 200) }}184 generate 10 HTML paragraphs between 50 and 200 words.185186 *new in Jinja 1.1*187188`watchchanges`189190 Jinja does not provide an django like ``{% ifchanged %}`` tag. As191 replacement for this tag there is a special function in the namespace192 called `watchchanges`.193194 You can use it like this:195196 .. sourcecode:: html+jinja197198 {% for changed, article in watchchanges(articles, 'date', 'day') %}199 {% if changed %}<h3>{{ articles.date.day }}</h3>{% endif %}200 <h4>{{ article.title|e }}</h4>201 <p>{{ article.body|e }}</p>202 {% endif %}203204 For each iteration `watchchanges` will check the given attribute. If it205 changed to the former iteration the first yielded item (in this example206 it's called `changed`) will be `true`, else `false`.207208 In this example `articles` is a list of articles for the template with209 an attribute called `date.day` which represents the current day. To only210 add a new day headline if the day has changed `watchchanges` is now told211 to check `articles.date.days`.212213 If you want to observe more than one attribute you can provide pairs:214215 .. sourcecode:: html+jinja216217 {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}218 ...219 {% endfor %}220221 Note that if you want to watch two first level attributes you have to222 either use the list syntax `[]` or add a colon:223224 .. sourcecode:: html+jinja225226 {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}227 ...228 {% endfor %}229230 otherwise Jinja cannot differ between a pair of parentheses to group231 expressions or the sequence syntax.232233 If you don't provide any arguments the value of the variable itself234 is checked.235236 *new in Jinja 1.1*23770Loops71=====7273To iterate over a sequence, you can use the `for` loop. It basically looks like a
9 unmodified lines
83 <li><em>no users found</em></li>84 {% endfor %}85 </ul>86255*Important* Contrary to Python is the optional ``else`` block only87*Important* Contrary to Python is the optional `else` block only88executed if there was no iteration because the sequence was empty.8990Inside of a `for` loop block you can access some special variables:91
255 unmodified lines
347348 If a macro parameter is called `varargs` the additional extra349 arguments are not accessible.350351For information regarding the visibility of macros have a look at the352`Scopes and Variable Behavior`_ section.353520Inheritance521===========522523The most powerful part of Jinja is template inheritance. Template inheritance524allows you to build a base "skeleton" template that contains all the common525elements of your site and defines **blocks** that child templates can override.526527Sounds complicated but is very basic. It's easiest to understand it by starting528with an example.529530Base Template531-------------532533This template, which we'll call ``base.html``, defines a simple HTML skeleton534document that you might use for a simple two-column page. It's the job of535"child" templates to fill the empty blocks with content:536537.. sourcecode:: html+jinja538539 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"540 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">541 <html xmlns="http://www.w3.org/1999/xhtml">542 <head>543 <link rel="stylesheet" href="style.css" />544 <title>{% block title %}{% endblock %} - My Webpage</title>545 {% block html_head %}{% endblock %}546 </head>547 <body>548 <div id="content">549 {% block content %}{% endblock %}550 </div>551552 <div id="footer">553 {% block footer %}554 &copy; Copyright 2006 by <a href="http://mydomain.tld">myself</a>.555 {% endblock %}556 </div>557 </body>558559In this example, the ``{% block %}`` tags define four blocks that child templates560can fill in. All the `block` tag does is to tell the template engine that a561child template may override those portions of the template.562563Child Template564--------------565566A child template might look like this:567568.. sourcecode:: html+jinja569570 {% extends "base.html" %}571 {% block title %}Index{% endblock %}572573 {% block html_head %}574 <style type="text/css">575 .important {576 color: #336699;577 }578 </style>579 {% endblock %}580 581 {% block content %}582 <h1>Index</h1>583 <p class="important">584 Welcome on my awsome homepage.585 </p>586 {% endblock %}587588The ``{% extends %}`` tag is the key here. It tells the template engine that589this template "extends" another template. When the template system evaluates590this template, first it locates the parent.591592The filename of the template depends on the template loader. For example the593``FileSystemLoader`` allows you to access other templates by giving the594filename. You can access templates in subdirectories with an slash:595596.. sourcecode:: jinja597598 {% extends "layout/default.html" %}599600But this behavior can depend on the application using Jinja.601602Note that since the child template didn't define the ``footer`` block, the603value from the parent template is used instead.604605.. admonition:: Note606607 You can't define multiple ``{% block %}`` tags with the same name in the608 same template. This limitation exists because a block tag works in "both"609 directions. That is, a block tag doesn't just provide a hole to fill - it610 also defines the content that fills the hole in the *parent*. If there were611 two similarly-named ``{% block %}`` tags in a template, that template's612 parent wouldn't know which one of the blocks' content to use.613614How Inheritance Works Internally615--------------------------------616617Inheritance in Jinja is straighforward. If a template contains a618``{% extends %}`` tag it's considered being a child template, otherwise it's619a layout template. In a layout template you can place blocks basically620everywhere. In a child template blocks can only be located either top level621or inside of another block.622623Data outside of a block in a child template is executed before the layout624template is rendered, thus you can use it to propagate data to the whole625inheritance chain. Having a block in an invalid position you will receive626an syntax error. Here some examples:627628**impossible**:629630 .. sourcecode:: jinja631632 {% extends 'master.html' %}633 {% if some_condition %}634 {% block body %}635 ...636 {% endblock %}637 {% endif %}638639 This can't work because template inheritance works at translation /640 compilation time not at template executation.641642**possible**:643644 .. sourcecode:: jinja645646 {% extends 'master.html' %}647 {% block body %}648 {% if some_condition %}649 {% block myblock %}650 ...651 {% endblock %}652 {% endblock %}653 {% endblock %}654655 This can work although it probably makes no sense in this specific case.656 However the condition is handled at runtime because it's in a valid block657 and defines a new block subtemplates can override.658659Super Blocks660============661662Starting with `Jinja 1.1` it's possible to render the contents of the parent663block. By calling it you get the results of the parent block back. If you want664to get the data of the parent you can give it an offset:665666.. sourcecode:: jinja667668 {{ super() }}669 return the parent data670671 {{ super(1) }}672 the same as above673674 {{ super(2) }}675 return the data of the second parent block676677354Template Inclusion355==================356357You can load another template at a given position using ``{% include %}``.
7 unmodified lines
365366If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now367use it from the template as shown above.368369Because of the370371Filtering Blocks372================373374Sometimes it could be a good idea to filter a complete block of text. For
28 unmodified lines
403 {{ foo }}404405This should ouput ``foobar``.406729Scopes730======407For information regarding the visibility of variables have a look at the408`Scopes and Variable Behavior`_ section.409732Jinja has multiple scopes. A scope is something like a new transparent foil on733a stack of foils. You can only write to the outermost foil but read all of them734since you can look through them. If you remove the top foil all data on that735foil disappears. Some tags in Jinja add a new layer to the stack. Currently736these are `block`, `for`, `macro` and `filter`. This means that variables and737other elements defined inside a macro, loop or some of the other tags listed738above will be only available in that block. Here an example:739740.. sourcecode:: jinja741742 {% macro angryhello name %}743 {% set angryname = name|upper %}744 Hello {{ name }}. Hello {{ name }}!745 HELLO {{ angryname }}!!!!!!111746 {% endmacro %}747748The variable ``angryname`` just exists inside the macro, not outside it.749750Defined macros appear on the context as variables. Because of this, they are751affected by the scoping too. A macro defined inside of a macro is just available752in those two macros (the macro itself and the macro it's defined in).753754Template Globals755================756757A special threatment exists for template code outside of visible blocks in758child templates. This code will be executed **before** the layout template759code. Thus it can be used to propagate values back to the layout template or760import macros from templates for rendering.761762Such code can output data but it won't appear in the final rendering. So no763additional whitespace will pollute the template.764765Because this code is executed before the actual layout template code it's766possible that the layout code overrides some of those variables. Usually767this is not a problem because of different variable names but it can be768a problem if you plan to specify default values.769770In that case you have to test if the variable is not defined before setting771it:772773.. sourcecode:: jinja774775 {% if not page_title %}776 {% set page_title = 'Default Page Title' %}777 {% endif %}778779You can of course also use the `|default` filter.780781.. admonition:: Explanation782783 This template stored as `a.html`:784785 .. sourcecode:: html+jinja786787 <title>{{ title|default('Untitled') }}</title>788 <body>{% block body %}{% endblock %}789790 ...and this child template stored as `b.html`:791792 .. sourcecode:: html+jinja793794 {% extends 'a.html' %}795 {% include 'macros.tmpl' %}796 {% set title = 'My Page' %}797 {% block body %}{{ wrap(42) }}{% endblock %}798799 ...and this code in `macros.tmpl`:800801 .. sourcecode:: html+jinja802803 {% macro wrap(text) %}804 [{{ text }}]805 {% endmacro %}806807 ..will translate to something with the same semantics as this (just808 that the value is not stored in a variable):809810 .. sourcecode:: html+jinja811812 {% filter capture('captured', true) %}813 {% macro wrap(text) %}814 [{{ text }}]815 {% endmacro %}816 {% set title='My Page' %}817 {% endfilter %}818 <title>{{ title|default('Untitled') }}</title>819 <body>820 {{ wrap(42) }}821 </body>822823.. admonition:: Note824825 This implementation was improved in Jinja 1.1. In Jinja 1.0 blocks that826 were not top-level were not propagated to the layout template. This made827 it impossible to use conditional expressions for inclusion in non root828 templates.829830831Undefined Variables832===================833834If you have already worked with python you probably know about the fact that835undefined variables raise an exception. This is different in Jinja. There is a836special value called `undefined` that represents values that do not exist.837838Depending on the configuration it will behave different.839840In order to check if a value is defined you can use the `defined` test:841842.. sourcecode:: jinja843844 {{ myvariable is not defined }}845 will return true if the variable does not exist.846847`SilentUndefined`:848849 The silent `undefined` is the default behavior. The `undefined` object works850 complete different from any variables you maybe know. If you print it851 using ``{{ variable }}`` it will not appear because it's literally empty.852 If you try to iterate over it, it will work. But no items are returned.853854 In order to check if a value is defined you can use the `defined` test:855856 There are also some additional rules regarding this special value. Any857 mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand858 as result:859860 .. sourcecode:: jinja861862 {{ undefined + "foo" }}863 returns "foo"864865 {{ undefined - 42 }}866 returns 42. Note: not -42!867868 In any expression `undefined` evaluates to `false`. It has no length, all869 attribute calls return undefined, calling too:870871 .. sourcecode:: jinja872873 {{ undefined.attribute().attribute_too[42] }}874 still returns `undefined`.875876`ComplainingUndefined`:877878 Starting with Jinja 1.1 it's possible to replace the default undefined879 object with different values. The other common undefined object which880 comes with Jinja is the `ComplainingUndefined` object.881882 It raises exceptions as soon as you either render it or want to iterate883 over it or try to access attributes etc.884 885886Escaping887========888889Sometimes you might want to add Jinja syntax elements into the template890without executing them. In that case you have quite a few possibilities.891892For small parts this might be a good way:893894.. sourcecode:: jinja895896 {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}897898When you have multiple elements you can use the ``raw`` block:899900.. sourcecode:: jinja901902 {% raw %}903 Filtering blocks works like this in Jinja:904 {% filter escape %}905 <html>906 <code>goes here</code>907 </html>908 {% endfilter %}909 {% endraw %}910410Reserved Keywords411=================412413Jinja has some keywords you cannot use a variable names. This limitation
20 unmodified lines
434means that they won't raise an error for several releases but yield warnings435on the application side. But it's very unlikely that new keywords will be436added.437939Global Constants940================438942Jinja provides some special variables which cannot be overridden in templates.943Those are not affected by the variable lookup:944945 `_`, `true`, `false`, `none`, `undefined`946947You cannot use those names for your own variables or macros. It's however no948problem to have blocks with that name.949950**Notice** due to a bug in Jinja 1.0 it was possible to override `_`, `true`,951`false`, `none` and `undefined` from the template by either using `{% set %}`952or in a for loop. While overriding `true`, `false` etc just caused nothing953overriding the translation marker `_` would crash the translation interface.954If you want to use `_` for unpacking in for loops (eg. skipping items) you955have to give it a proper name:956957.. sourcecode:: jinja958959 {% for key, ignore in mydict|dictsort %}960 {{ key|e }}961 {% endfor %}962963Whitespace964==========965966If the Jinja environment was created with ``trim_blocks`` set to true the967first newline after a template tag is removed automatically (php like968processing).969970Starting with `Jinja 1.1` you can also handle some whitespace rules in the971template. If you put an minus sign (`-`) to the start or end of an block972(for example a `for` tag) or a comment, variable element you can remove973the whitespaces after that block or before that block:974975.. sourcecode:: jinja976977 {% for item in seq -%}978 {{ item }}979 {%- endfor %}980981This will yield all elements without whitespace between them because they982are automatically removed. This of course works for other tags too:983984.. sourcecode:: jinja985986 {% for user in userlist -%}987 {{ user|e -}}988 {% if not loop.last %},{% endif %}989 {%- endfor %}990991Note that you must not use a whitespace between the tag and the minus sign:992993.. sourcecode:: jinja994995 valid:996 {%- if foo -%}...{% endif %}997998 invalid:9991000 {% - if foo - %}...{% endif %}10011002Internationalization1003====================10041005If the application is configured for i18n, you can define translatable blocks1006for translators using the `trans` tag or the special underscore function:10071008.. sourcecode:: jinja10091010 {% trans %}1011 this is a translatable block1012 {% endtrans %}10131014 {% trans "This is a translatable string" %}10151016 {{ _("This is a translatable string") }}10171018The latter one is useful if you want translatable arguments for filters etc.10191020If you want to have plural forms too, use the `pluralize` block:10211022.. sourcecode:: jinja10231024 {% trans users=users %}1025 One user found.1026 {% pluralize %}1027 {{ users }} users found.1028 {% endtrans %}10291030 {% trans first=(users|first).username|escape, user=users|length %}1031 one user {{ first }} found.1032 {% pluralize users %}1033 {{ users }} users found, the first one is called {{ first }}.1034 {% endtrans %}10351036If you have multiple arguments, the first one is assumed to be the indicator (the1037number that is used to determine the correct singular or plural form. If you1038don't have the indicator variable on position 1 you have to tell the `pluralize`1039tag the correct variable name.10401041Inside translatable blocks you cannot use blocks or expressions (however you can1042still use the ``raw`` block which will work as expected). The variable1043print syntax (``{{ variablename }}``) is the only way to insert the variables1044defined in the ``trans`` header. Filters must be applied in the header.10451046.. admonition:: note10471048 Please make sure that you always use pluralize blocks where required.1049 Many languages have more complex plural forms than the English language.1050 1051 Never try to workaround that issue by using something like this:10521053 .. sourcecode:: jinja10541055 {% if count != 1 %}1056 {{ count }} users found.1057 {% else %}1058 one user found.1059 {% endif %}10601061*New in Jinja 1.1*: It's now possible to use the marker name as implicit1062default:10631064.. sourcecode:: jinja10651066 instead of this version:10671068 {% trans username=username %}Hello {{ username }}!{% endtrans %}10691070 you can now write this:10711072 {% trans username %}Hello {{ username }}!{% endtrans %}10731074439Bleeding Edge440=============441442Here are some features documented that are new in the SVN version and might
53 unmodified lines
496 <li>[[6]]</li>497 </ul>498499.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice1136.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000500.. _Scopes and Variable Behavior: scopes.txt
added:docs/src/escaping.txt+71 added
1=======================2Whitespace and Escaping3=======================45This section of the documentation explains how to remove unused whitespace6from the templates and embed raw Jinja syntax.78Escaping9========1011Sometimes you might want to add Jinja syntax elements into the template12without executing them. In that case you have quite a few possibilities.1314For small parts this might be a good way:1516.. sourcecode:: jinja1718 {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}1920When you have multiple elements you can use the ``raw`` block:2122.. sourcecode:: jinja2324 {% raw %}25 Filtering blocks works like this in Jinja:26 {% filter escape %}27 <html>28 <code>goes here</code>29 </html>30 {% endfilter %}31 {% endraw %}323334Whitespace35==========3637If the Jinja environment was created with ``trim_blocks`` set to true the38first newline after a template tag is removed automatically (php like39processing).4041Starting with `Jinja 1.1` you can also handle some whitespace rules in the42template. If you put an minus sign (`-`) to the start or end of an block43(for example a `for` tag) or a comment, variable element you can remove44the whitespaces after that block or before that block:4546.. sourcecode:: jinja4748 {% for item in seq -%}49 {{ item }}50 {%- endfor %}5152This will yield all elements without whitespace between them because they53are automatically removed. This of course works for other tags too:5455.. sourcecode:: jinja5657 {% for user in userlist -%}58 {{ user|e -}}59 {% if not loop.last %},{% endif %}60 {%- endfor %}6162Note that you must not use a whitespace between the tag and the minus sign:6364.. sourcecode:: jinja6566 valid:67 {%- if foo -%}...{% endif %}6869 invalid:7071 {% - if foo - %}...{% endif %}
modified:docs/src/index.txt+16 added-2 removed
45 unmodified lines
46 developers.4748- **Template Designer Documentation**:4950 - `Syntax Reference <designerdoc.txt>`_ - the designer documentation. Put51 this under your pillow.50 - `Syntax Reference <designerdoc.txt>`_ - quick overview over the Jinja51 syntax elements.5253 - `Template Inheritance <inheritance.txt>`_ - template inheritance howto.5455 - `Filters, Tests and Helper Functions <builtins.txt>`_ - list of filters56 and test/helper functions.5758 - `Whitespace and Escaping <escaping.txt>`_ - how to escape markup and59 control whitespace.6061 - `Scopes and Variable Behavior <scopes.txt>`_ - behavior of undefined62 variables and scoping rules.6364 - `Template Internationalization <templatei18n.txt>`_ - how to internationalize65 Jinja templates.6667 - `Differences To Django <fromdjango.txt>`_ - coming from django? Then this68 document is for you.6970 - `Designer Recipies <recipies.txt>`_ - various tips and tricks for designers.
4 unmodified lines
added:docs/src/inheritance.txt+157 added
1====================2Template Inheritance3====================45The most powerful part of Jinja is template inheritance. Template inheritance6allows you to build a base "skeleton" template that contains all the common7elements of your site and defines **blocks** that child templates can override.89Sounds complicated but is very basic. It's easiest to understand it by starting10with an example.1112Base Template13=============1415This template, which we'll call ``base.html``, defines a simple HTML skeleton16document that you might use for a simple two-column page. It's the job of17"child" templates to fill the empty blocks with content:1819.. sourcecode:: html+jinja2021 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"22 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">23 <html xmlns="http://www.w3.org/1999/xhtml">24 <head>25 <link rel="stylesheet" href="style.css" />26 <title>{% block title %}{% endblock %} - My Webpage</title>27 {% block html_head %}{% endblock %}28 </head>29 <body>30 <div id="content">31 {% block content %}{% endblock %}32 </div>3334 <div id="footer">35 {% block footer %}36 &copy; Copyright 2006 by <a href="http://mydomain.tld">myself</a>.37 {% endblock %}38 </div>39 </body>4041In this example, the ``{% block %}`` tags define four blocks that child templates42can fill in. All the `block` tag does is to tell the template engine that a43child template may override those portions of the template.4445Child Template46==============4748A child template might look like this:4950.. sourcecode:: html+jinja5152 {% extends "base.html" %}53 {% block title %}Index{% endblock %}5455 {% block html_head %}56 <style type="text/css">57 .important {58 color: #336699;59 }60 </style>61 {% endblock %}62 63 {% block content %}64 <h1>Index</h1>65 <p class="important">66 Welcome on my awsome homepage.67 </p>68 {% endblock %}6970The ``{% extends %}`` tag is the key here. It tells the template engine that71this template "extends" another template. When the template system evaluates72this template, first it locates the parent.7374The filename of the template depends on the template loader. For example the75``FileSystemLoader`` allows you to access other templates by giving the76filename. You can access templates in subdirectories with an slash:7778.. sourcecode:: jinja7980 {% extends "layout/default.html" %}8182But this behavior can depend on the application using Jinja.8384Note that since the child template didn't define the ``footer`` block, the85value from the parent template is used instead.8687.. admonition:: Note8889 You can't define multiple ``{% block %}`` tags with the same name in the90 same template. This limitation exists because a block tag works in "both"91 directions. That is, a block tag doesn't just provide a hole to fill - it92 also defines the content that fills the hole in the *parent*. If there were93 two similarly-named ``{% block %}`` tags in a template, that template's94 parent wouldn't know which one of the blocks' content to use.9596How Inheritance Works Internally97================================9899Inheritance in Jinja is straighforward. If a template contains a100``{% extends %}`` tag it's considered being a child template, otherwise it's101a layout template. In a layout template you can place blocks basically102everywhere. In a child template blocks can only be located either top level103or inside of another block.104105Data outside of a block in a child template is executed before the layout106template is rendered, thus you can use it to propagate data to the whole107inheritance chain. Having a block in an invalid position you will receive108an syntax error. Here some examples:109110**impossible**:111112 .. sourcecode:: jinja113114 {% extends 'master.html' %}115 {% if some_condition %}116 {% block body %}117 ...118 {% endblock %}119 {% endif %}120121 This can't work because template inheritance works at translation /122 compilation time not at template executation.123124**possible**:125126 .. sourcecode:: jinja127128 {% extends 'master.html' %}129 {% block body %}130 {% if some_condition %}131 {% block myblock %}132 ...133 {% endblock %}134 {% endblock %}135 {% endblock %}136137 This can work although it probably makes no sense in this specific case.138 However the condition is handled at runtime because it's in a valid block139 and defines a new block subtemplates can override.140141Super Blocks142============143144Starting with `Jinja 1.1` it's possible to render the contents of the parent145block. By calling it you get the results of the parent block back. If you want146to get the data of the parent you can give it an offset:147148.. sourcecode:: jinja149150 {{ super() }}151 return the parent data152153 {{ super(1) }}154 the same as above155156 {{ super(2) }}157 return the data of the second parent block
modified:docs/src/objects.txt+2 added-3 removed
88 unmodified lines
89 class MyModel(...):9091 # just give access to a and b. Default is all92 # note that this also disallows the functions from below.93 # if you use jinja_allowed_attributes you don't have to94 # do the code below because methods are threaded as attributes95 # too.93 # if you use jinja_allowed_attributes you don't have add the94 # code below since methods are treated as attributes too.95 jinja_allowed_attributes = ['a', 'b']9697 def __init__(self, ...):98 ...
31 unmodified lines
added:docs/src/scopes.txt+161 added
1============================2Scopes and Variable Behavior3============================45This section of the documentation covers the Jinja behavior regarding6variable visibility.78Scopes9======1011Jinja has multiple scopes. A scope is something like a new transparent foil on12a stack of foils. You can only write to the outermost foil but read all of them13since you can look through them. If you remove the top foil all data on that14foil disappears. Some tags in Jinja add a new layer to the stack. Currently15these are `block`, `for`, `macro` and `filter`. This means that variables and16other elements defined inside a macro, loop or some of the other tags listed17above will be only available in that block. Here an example:1819.. sourcecode:: jinja2021 {% macro angryhello name %}22 {% set angryname = name|upper %}23 Hello {{ name }}. Hello {{ name }}!24 HELLO {{ angryname }}!!!!!!11125 {% endmacro %}2627The variable ``angryname`` just exists inside the macro, not outside it.2829Defined macros appear on the context as variables. Because of this, they are30affected by the scoping too. A macro defined inside of a macro is just available31in those two macros (the macro itself and the macro it's defined in).3233Template Globals34================3536A special threatment exists for template code outside of visible blocks in37child templates. This code will be executed **before** the layout template38code. Thus it can be used to propagate values back to the layout template or39import macros from templates for rendering.4041Such code can output data but it won't appear in the final rendering. So no42additional whitespace will pollute the template.4344Because this code is executed before the actual layout template code it's45possible that the layout code overrides some of those variables. Usually46this is not a problem because of different variable names but it can be47a problem if you plan to specify default values.4849In that case you have to test if the variable is not defined before setting50it:5152.. sourcecode:: jinja5354 {% if not page_title %}55 {% set page_title = 'Default Page Title' %}56 {% endif %}5758You can of course also use the `|default` filter.5960.. admonition:: Explanation6162 This template stored as `a.html`:6364 .. sourcecode:: html+jinja6566 <title>{{ title|default('Untitled') }}</title>67 <body>{% block body %}{% endblock %}6869 ...and this child template stored as `b.html`:7071 .. sourcecode:: html+jinja7273 {% extends 'a.html' %}74 {% include 'macros.tmpl' %}75 {% set title = 'My Page' %}76 {% block body %}{{ wrap(42) }}{% endblock %}7778 ...and this code in `macros.tmpl`:7980 .. sourcecode:: html+jinja8182 {% macro wrap(text) %}83 [{{ text }}]84 {% endmacro %}8586 ..will translate to something with the same semantics as this (just87 that the value is not stored in a variable):8889 .. sourcecode:: html+jinja9091 {% filter capture('captured', true) %}92 {% macro wrap(text) %}93 [{{ text }}]94 {% endmacro %}95 {% set title='My Page' %}96 {% endfilter %}97 <title>{{ title|default('Untitled') }}</title>98 <body>99 {{ wrap(42) }}100 </body>101102.. admonition:: Note103104 This implementation was improved in Jinja 1.1. In Jinja 1.0 blocks that105 were not top-level were not propagated to the layout template. This made106 it impossible to use conditional expressions for inclusion in non root107 templates.108109Undefined Variables110===================111112If you have already worked with python you probably know about the fact that113undefined variables raise an exception. This is different in Jinja. There is a114special value called `undefined` that represents values that do not exist.115116Depending on the configuration it will behave different.117118In order to check if a value is defined you can use the `defined` test:119120.. sourcecode:: jinja121122 {{ myvariable is not defined }}123 will return true if the variable does not exist.124125`SilentUndefined`:126127 The silent `undefined` is the default behavior. The `undefined` object works128 complete different from any variables you maybe know. If you print it129 using ``{{ variable }}`` it will not appear because it's literally empty.130 If you try to iterate over it, it will work. But no items are returned.131132 In order to check if a value is defined you can use the `defined` test:133134 There are also some additional rules regarding this special value. Any135 mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand136 as result:137138 .. sourcecode:: jinja139140 {{ undefined + "foo" }}141 returns "foo"142143 {{ undefined - 42 }}144 returns 42. Note: not -42!145146 In any expression `undefined` evaluates to `false`. It has no length, all147 attribute calls return undefined, calling too:148149 .. sourcecode:: jinja150151 {{ undefined.attribute().attribute_too[42] }}152 still returns `undefined`.153154`ComplainingUndefined`:155156 Starting with Jinja 1.1 it's possible to replace the default undefined157 object with different values. The other common undefined object which158 comes with Jinja is the `ComplainingUndefined` object.159160 It raises exceptions as soon as you either render it or want to iterate161 over it or try to access attributes etc.
added:docs/src/templatei18n.txt+72 added
1=============================2Template Internationalization3=============================45If the application is configured for i18n, you can define translatable blocks6for translators using the `trans` tag or the special underscore function:78.. sourcecode:: jinja910 {% trans %}11 this is a translatable block12 {% endtrans %}1314 {% trans "This is a translatable string" %}1516 {{ _("This is a translatable string") }}1718The latter one is useful if you want translatable arguments for filters etc.1920If you want to have plural forms too, use the `pluralize` block:2122.. sourcecode:: jinja2324 {% trans users=users %}25 One user found.26 {% pluralize %}27 {{ users }} users found.28 {% endtrans %}2930 {% trans first=(users|first).username|escape, user=users|length %}31 one user {{ first }} found.32 {% pluralize users %}33 {{ users }} users found, the first one is called {{ first }}.34 {% endtrans %}3536If you have multiple arguments, the first one is assumed to be the indicator (the37number that is used to determine the correct singular or plural form. If you38don't have the indicator variable on position 1 you have to tell the `pluralize`39tag the correct variable name.4041Inside translatable blocks you cannot use blocks or expressions (however you can42still use the ``raw`` block which will work as expected). The variable43print syntax (``{{ variablename }}``) is the only way to insert the variables44defined in the ``trans`` header. Filters must be applied in the header.4546.. admonition:: note4748 Please make sure that you always use pluralize blocks where required.49 Many languages have more complex plural forms than the English language.50 51 Never try to workaround that issue by using something like this:5253 .. sourcecode:: jinja5455 {% if count != 1 %}56 {{ count }} users found.57 {% else %}58 one user found.59 {% endif %}6061*New in Jinja 1.1*: It's now possible to use the marker name as implicit62default:6364.. sourcecode:: jinja6566 instead of this version:6768 {% trans username=username %}Hello {{ username }}!{% endtrans %}6970 you can now write this:7172 {% trans username %}Hello {{ username }}!{% endtrans %}