[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
Provenance
- Commit
4c9cfcc- Tree
d176f00- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
44fb2e1
8 files changed+690 added−649 removed
added:docs/src/builtins.txt+203 added
1+===================================2+Filters, Tests and Helper Functions3+===================================4+5+This part of the documentation lists the filter-, test- and helper functions6+you can use in templates.7+8+9+Filters10+=======11+12+In the examples above you might have noticed the pipe symbols. Pipe symbols tell13+the engine that it has to apply a filter on the variable. Here is a small example:14+15+.. sourcecode:: jinja16+17+ {{ variable|replace('foo', 'bar')|escape }}18+19+If you want, you can also put whitespace between the filters.20+21+This will look for a variable `variable`, pass it to the filter `replace`22+with 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:25+26+[[list_of_filters]]27+28+.. admonition:: note29+30+ 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:33+34+ .. sourcecode:: jinja35+36+ correct:37+ {{ (foo|filter) + (bar|filter) }}38+ wrong:39+ {{ foo|filter + bar|filter }}40+41+ correct:42+ {{ (foo|filter).attribute }}43+ wrong:44+ {{ foo|filter.attribute }}45+46+*new in Jinja 1.1*:47+48+Because the application can provide additional filters you can get a documentation49+of all the provided filters by calling ``debug.filters()``:50+51+.. sourcecode:: jinja52+53+ {{ debug.filters() }}54+ -> returns a plain text representation of all the filters55+56+ {{ debug.filters(False) }}57+ -> same as above but without the builtin ones.58+59+Tests60+=====61+62+You can use the `is` operator to perform tests on a value:63+64+.. sourcecode:: jinja65+66+ {{ 42 is numeric }} -> true67+ {{ "foobar" is numeric }} -> false68+ {{ 'FOO' is upper }} -> true69+70+These tests are especially useful when used in `if` conditions.71+72+[[list_of_tests]]73+74+*new in Jinja 1.1*:75+76+Because the application can provide additional tests you can get a documentation77+of all the provided tests by calling ``debug.tests()``:78+79+.. sourcecode:: jinja80+81+ {{ debug.tests() }}82+ -> returns a plain text representation of all the tests83+84+ {{ debug.tests(False) }}85+ -> same as above but without the builtin ones.86+87+88+Global Functions89+================90+91+Test functions and filter functions live in their own namespace. Global92+functions not. They behave like normal objects in the context. Beside the93+functions added by the application or framewhere there are two functions94+available per default:95+96+`range`97+ 98+ Works like the python `range function`_ just that it doesn't support99+ ranges greater than ``1000000``.100+101+`debug`102+103+ Function that outputs the contents of the context.104+105+`lipsum`106+107+ Generate some paragraphs of random text:108+109+ .. sourcecode:: jinja110+111+ {{ lipsum(5) }}112+ five html paragraphs113+114+ {{ lipsum(2, False) }}115+ two ascii only paragraphs116+117+ Per default a paragraph is between 20 and 100 words long. You can118+ override this default with the third and fourth parameter:119+120+ .. sourcecode:: jinja121+122+ {{ lipsum(10, True, 50, 200) }}123+ generate 10 HTML paragraphs between 50 and 200 words.124+125+ *new in Jinja 1.1*126+127+`watchchanges`128+129+ Jinja does not provide an django like ``{% ifchanged %}`` tag. As130+ replacement for this tag there is a special function in the namespace131+ called `watchchanges`.132+133+ You can use it like this:134+135+ .. sourcecode:: html+jinja136+137+ {% 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 %}142+143+ 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`.146+147+ 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`.151+152+ If you want to observe more than one attribute you can provide pairs:153+154+ .. sourcecode:: html+jinja155+156+ {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}157+ ...158+ {% endfor %}159+160+ Note that if you want to watch two first level attributes you have to161+ either use the list syntax `[]` or add a colon:162+163+ .. sourcecode:: html+jinja164+165+ {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}166+ ...167+ {% endfor %}168+169+ otherwise Jinja cannot differ between a pair of parentheses to group170+ expressions or the sequence syntax.171+172+ If you don't provide any arguments the value of the variable itself173+ is checked.174+175+ *new in Jinja 1.1*176+177+178+Global Constants179+================180+181+Jinja provides some special variables which cannot be overridden in templates.182+Those are not affected by the variable lookup:183+184+ `_`, `true`, `false`, `none`, `undefined`185+186+You cannot use those names for your own variables or macros. It's however no187+problem to have blocks with that name.188+189+**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 %}`191+or in a for loop. While overriding `true`, `false` etc just caused nothing192+overriding the translation marker `_` would crash the translation interface.193+If you want to use `_` for unpacking in for loops (eg. skipping items) you194+have to give it a proper name:195+196+.. sourcecode:: jinja197+198+ {% for key, ignore in mydict|dictsort %}199+ {{ key|e }}200+ {% endfor %}201+202+203+.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000modified:docs/src/designerdoc.txt+8 added-644 removed
65 unmodified lines66 {{ users[current_user].username }}67 If you have numerical indices you have to use the [] syntax:68 {{ users[0].username }}69 70-Filters71-=======72-73-In the examples above you might have noticed the pipe symbols. Pipe symbols tell74-the engine that it has to apply a filter on the variable. Here is a small example:75-76-.. sourcecode:: jinja77-78- {{ variable|replace('foo', 'bar')|escape }}79-80-If you want, you can also put whitespace between the filters.81-82-This will look for a variable `variable`, pass it to the filter `replace`83-with 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:86-87-[[list_of_filters]]88-89-.. admonition:: note90-91- 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:94-95- .. sourcecode:: jinja96-97- correct:98- {{ (foo|filter) + (bar|filter) }}99- wrong:100- {{ foo|filter + bar|filter }}101-102- correct:103- {{ (foo|filter).attribute }}104- wrong:105- {{ foo|filter.attribute }}106-107-*new in Jinja 1.1*:108-109-Because the application can provide additional filters you can get a documentation110-of all the provided filters by calling ``debug.filters()``:111-112-.. sourcecode:: jinja113-114- {{ debug.filters() }}115- -> returns a plain text representation of all the filters116-117- {{ debug.filters(False) }}118- -> same as above but without the builtin ones.119-120-Tests121-=====122-123-You can use the `is` operator to perform tests on a value:124-125-.. sourcecode:: jinja126-127- {{ 42 is numeric }} -> true128- {{ "foobar" is numeric }} -> false129- {{ 'FOO' is upper }} -> true130-131-These tests are especially useful when used in `if` conditions.132-133-[[list_of_tests]]134-135-*new in Jinja 1.1*:136-137-Because the application can provide additional tests you can get a documentation138-of all the provided tests by calling ``debug.tests()``:139-140-.. sourcecode:: jinja141-142- {{ debug.tests() }}143- -> returns a plain text representation of all the tests144-145- {{ debug.tests(False) }}146- -> same as above but without the builtin ones.147-148-149-Global Functions150-================151-152-Test functions and filter functions live in their own namespace. Global153-functions not. They behave like normal objects in the context. Beside the154-functions added by the application or framewhere there are two functions155-available per default:156-157-`range`158- 159- Works like the python `range function`_ just that it doesn't support160- ranges greater than ``1000000``.161-162-`debug`163-164- Function that outputs the contents of the context.165-166-`lipsum`167-168- Generate some paragraphs of random text:169-170- .. sourcecode:: jinja171-172- {{ lipsum(5) }}173- five html paragraphs174-175- {{ lipsum(2, False) }}176- two ascii only paragraphs177-178- Per default a paragraph is between 20 and 100 words long. You can179- override this default with the third and fourth parameter:180-181- .. sourcecode:: jinja182-183- {{ lipsum(10, True, 50, 200) }}184- generate 10 HTML paragraphs between 50 and 200 words.185-186- *new in Jinja 1.1*187-188-`watchchanges`189-190- Jinja does not provide an django like ``{% ifchanged %}`` tag. As191- replacement for this tag there is a special function in the namespace192- called `watchchanges`.193-194- You can use it like this:195-196- .. sourcecode:: html+jinja197-198- {% 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 %}203-204- 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`.207-208- 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`.212-213- If you want to observe more than one attribute you can provide pairs:214-215- .. sourcecode:: html+jinja216-217- {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}218- ...219- {% endfor %}220-221- Note that if you want to watch two first level attributes you have to222- either use the list syntax `[]` or add a colon:223-224- .. sourcecode:: html+jinja225-226- {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}227- ...228- {% endfor %}229-230- otherwise Jinja cannot differ between a pair of parentheses to group231- expressions or the sequence syntax.232-233- If you don't provide any arguments the value of the variable itself234- is checked.235-236- *new in Jinja 1.1*237-70 Loops71 =====72 73 To iterate over a sequence, you can use the `for` loop. It basically looks like a9 unmodified lines83 <li><em>no users found</em></li>84 {% endfor %}85 </ul>86 255-*Important* Contrary to Python is the optional ``else`` block only87+*Important* Contrary to Python is the optional `else` block only88 executed if there was no iteration because the sequence was empty.89 90 Inside of a `for` loop block you can access some special variables:91 255 unmodified lines347 348 If a macro parameter is called `varargs` the additional extra349 arguments are not accessible.350 351+For information regarding the visibility of macros have a look at the352+`Scopes and Variable Behavior`_ section.353 520-Inheritance521-===========522-523-The most powerful part of Jinja is template inheritance. Template inheritance524-allows you to build a base "skeleton" template that contains all the common525-elements of your site and defines **blocks** that child templates can override.526-527-Sounds complicated but is very basic. It's easiest to understand it by starting528-with an example.529-530-Base Template531--------------532-533-This template, which we'll call ``base.html``, defines a simple HTML skeleton534-document that you might use for a simple two-column page. It's the job of535-"child" templates to fill the empty blocks with content:536-537-.. sourcecode:: html+jinja538-539- <!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>551-552- <div id="footer">553- {% block footer %}554- © Copyright 2006 by <a href="http://mydomain.tld">myself</a>.555- {% endblock %}556- </div>557- </body>558-559-In this example, the ``{% block %}`` tags define four blocks that child templates560-can fill in. All the `block` tag does is to tell the template engine that a561-child template may override those portions of the template.562-563-Child Template564---------------565-566-A child template might look like this:567-568-.. sourcecode:: html+jinja569-570- {% extends "base.html" %}571- {% block title %}Index{% endblock %}572-573- {% 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 %}587-588-The ``{% extends %}`` tag is the key here. It tells the template engine that589-this template "extends" another template. When the template system evaluates590-this template, first it locates the parent.591-592-The filename of the template depends on the template loader. For example the593-``FileSystemLoader`` allows you to access other templates by giving the594-filename. You can access templates in subdirectories with an slash:595-596-.. sourcecode:: jinja597-598- {% extends "layout/default.html" %}599-600-But this behavior can depend on the application using Jinja.601-602-Note that since the child template didn't define the ``footer`` block, the603-value from the parent template is used instead.604-605-.. admonition:: Note606-607- 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.613-614-How Inheritance Works Internally615---------------------------------616-617-Inheritance in Jinja is straighforward. If a template contains a618-``{% extends %}`` tag it's considered being a child template, otherwise it's619-a layout template. In a layout template you can place blocks basically620-everywhere. In a child template blocks can only be located either top level621-or inside of another block.622-623-Data outside of a block in a child template is executed before the layout624-template is rendered, thus you can use it to propagate data to the whole625-inheritance chain. Having a block in an invalid position you will receive626-an syntax error. Here some examples:627-628-**impossible**:629-630- .. sourcecode:: jinja631-632- {% extends 'master.html' %}633- {% if some_condition %}634- {% block body %}635- ...636- {% endblock %}637- {% endif %}638-639- This can't work because template inheritance works at translation /640- compilation time not at template executation.641-642-**possible**:643-644- .. sourcecode:: jinja645-646- {% extends 'master.html' %}647- {% block body %}648- {% if some_condition %}649- {% block myblock %}650- ...651- {% endblock %}652- {% endblock %}653- {% endblock %}654-655- 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.658-659-Super Blocks660-============661-662-Starting with `Jinja 1.1` it's possible to render the contents of the parent663-block. By calling it you get the results of the parent block back. If you want664-to get the data of the parent you can give it an offset:665-666-.. sourcecode:: jinja667-668- {{ super() }}669- return the parent data670-671- {{ super(1) }}672- the same as above673-674- {{ super(2) }}675- return the data of the second parent block676-677-354 Template Inclusion355 ==================356 357 You can load another template at a given position using ``{% include %}``.7 unmodified lines365 366 If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now367 use it from the template as shown above.368 369+Because of the370+371 Filtering Blocks372 ================373 374 Sometimes it could be a good idea to filter a complete block of text. For28 unmodified lines403 {{ foo }}404 405 This should ouput ``foobar``.406 729-Scopes730-======407+For information regarding the visibility of variables have a look at the408+`Scopes and Variable Behavior`_ section.409 732-Jinja has multiple scopes. A scope is something like a new transparent foil on733-a stack of foils. You can only write to the outermost foil but read all of them734-since you can look through them. If you remove the top foil all data on that735-foil disappears. Some tags in Jinja add a new layer to the stack. Currently736-these are `block`, `for`, `macro` and `filter`. This means that variables and737-other elements defined inside a macro, loop or some of the other tags listed738-above will be only available in that block. Here an example:739-740-.. sourcecode:: jinja741-742- {% macro angryhello name %}743- {% set angryname = name|upper %}744- Hello {{ name }}. Hello {{ name }}!745- HELLO {{ angryname }}!!!!!!111746- {% endmacro %}747-748-The variable ``angryname`` just exists inside the macro, not outside it.749-750-Defined macros appear on the context as variables. Because of this, they are751-affected by the scoping too. A macro defined inside of a macro is just available752-in those two macros (the macro itself and the macro it's defined in).753-754-Template Globals755-================756-757-A special threatment exists for template code outside of visible blocks in758-child templates. This code will be executed **before** the layout template759-code. Thus it can be used to propagate values back to the layout template or760-import macros from templates for rendering.761-762-Such code can output data but it won't appear in the final rendering. So no763-additional whitespace will pollute the template.764-765-Because this code is executed before the actual layout template code it's766-possible that the layout code overrides some of those variables. Usually767-this is not a problem because of different variable names but it can be768-a problem if you plan to specify default values.769-770-In that case you have to test if the variable is not defined before setting771-it:772-773-.. sourcecode:: jinja774-775- {% if not page_title %}776- {% set page_title = 'Default Page Title' %}777- {% endif %}778-779-You can of course also use the `|default` filter.780-781-.. admonition:: Explanation782-783- This template stored as `a.html`:784-785- .. sourcecode:: html+jinja786-787- <title>{{ title|default('Untitled') }}</title>788- <body>{% block body %}{% endblock %}789-790- ...and this child template stored as `b.html`:791-792- .. sourcecode:: html+jinja793-794- {% extends 'a.html' %}795- {% include 'macros.tmpl' %}796- {% set title = 'My Page' %}797- {% block body %}{{ wrap(42) }}{% endblock %}798-799- ...and this code in `macros.tmpl`:800-801- .. sourcecode:: html+jinja802-803- {% macro wrap(text) %}804- [{{ text }}]805- {% endmacro %}806-807- ..will translate to something with the same semantics as this (just808- that the value is not stored in a variable):809-810- .. sourcecode:: html+jinja811-812- {% 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>822-823-.. admonition:: Note824-825- 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.829-830-831-Undefined Variables832-===================833-834-If you have already worked with python you probably know about the fact that835-undefined variables raise an exception. This is different in Jinja. There is a836-special value called `undefined` that represents values that do not exist.837-838-Depending on the configuration it will behave different.839-840-In order to check if a value is defined you can use the `defined` test:841-842-.. sourcecode:: jinja843-844- {{ myvariable is not defined }}845- will return true if the variable does not exist.846-847-`SilentUndefined`:848-849- 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.853-854- In order to check if a value is defined you can use the `defined` test:855-856- There are also some additional rules regarding this special value. Any857- mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand858- as result:859-860- .. sourcecode:: jinja861-862- {{ undefined + "foo" }}863- returns "foo"864-865- {{ undefined - 42 }}866- returns 42. Note: not -42!867-868- In any expression `undefined` evaluates to `false`. It has no length, all869- attribute calls return undefined, calling too:870-871- .. sourcecode:: jinja872-873- {{ undefined.attribute().attribute_too[42] }}874- still returns `undefined`.875-876-`ComplainingUndefined`:877-878- 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.881-882- It raises exceptions as soon as you either render it or want to iterate883- over it or try to access attributes etc.884- 885-886-Escaping887-========888-889-Sometimes you might want to add Jinja syntax elements into the template890-without executing them. In that case you have quite a few possibilities.891-892-For small parts this might be a good way:893-894-.. sourcecode:: jinja895-896- {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}897-898-When you have multiple elements you can use the ``raw`` block:899-900-.. sourcecode:: jinja901-902- {% 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 %}910-410 Reserved Keywords411 =================412 413 Jinja has some keywords you cannot use a variable names. This limitation20 unmodified lines434 means that they won't raise an error for several releases but yield warnings435 on the application side. But it's very unlikely that new keywords will be436 added.437 939-Global Constants940-================438 942-Jinja provides some special variables which cannot be overridden in templates.943-Those are not affected by the variable lookup:944-945- `_`, `true`, `false`, `none`, `undefined`946-947-You cannot use those names for your own variables or macros. It's however no948-problem to have blocks with that name.949-950-**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 %}`952-or in a for loop. While overriding `true`, `false` etc just caused nothing953-overriding the translation marker `_` would crash the translation interface.954-If you want to use `_` for unpacking in for loops (eg. skipping items) you955-have to give it a proper name:956-957-.. sourcecode:: jinja958-959- {% for key, ignore in mydict|dictsort %}960- {{ key|e }}961- {% endfor %}962-963-Whitespace964-==========965-966-If the Jinja environment was created with ``trim_blocks`` set to true the967-first newline after a template tag is removed automatically (php like968-processing).969-970-Starting with `Jinja 1.1` you can also handle some whitespace rules in the971-template. 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 remove973-the whitespaces after that block or before that block:974-975-.. sourcecode:: jinja976-977- {% for item in seq -%}978- {{ item }}979- {%- endfor %}980-981-This will yield all elements without whitespace between them because they982-are automatically removed. This of course works for other tags too:983-984-.. sourcecode:: jinja985-986- {% for user in userlist -%}987- {{ user|e -}}988- {% if not loop.last %},{% endif %}989- {%- endfor %}990-991-Note that you must not use a whitespace between the tag and the minus sign:992-993-.. sourcecode:: jinja994-995- valid:996- {%- if foo -%}...{% endif %}997-998- invalid:999-1000- {% - if foo - %}...{% endif %}1001-1002-Internationalization1003-====================1004-1005-If the application is configured for i18n, you can define translatable blocks1006-for translators using the `trans` tag or the special underscore function:1007-1008-.. sourcecode:: jinja1009-1010- {% trans %}1011- this is a translatable block1012- {% endtrans %}1013-1014- {% trans "This is a translatable string" %}1015-1016- {{ _("This is a translatable string") }}1017-1018-The latter one is useful if you want translatable arguments for filters etc.1019-1020-If you want to have plural forms too, use the `pluralize` block:1021-1022-.. sourcecode:: jinja1023-1024- {% trans users=users %}1025- One user found.1026- {% pluralize %}1027- {{ users }} users found.1028- {% endtrans %}1029-1030- {% 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 %}1035-1036-If you have multiple arguments, the first one is assumed to be the indicator (the1037-number that is used to determine the correct singular or plural form. If you1038-don't have the indicator variable on position 1 you have to tell the `pluralize`1039-tag the correct variable name.1040-1041-Inside translatable blocks you cannot use blocks or expressions (however you can1042-still use the ``raw`` block which will work as expected). The variable1043-print syntax (``{{ variablename }}``) is the only way to insert the variables1044-defined in the ``trans`` header. Filters must be applied in the header.1045-1046-.. admonition:: note1047-1048- 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:1052-1053- .. sourcecode:: jinja1054-1055- {% if count != 1 %}1056- {{ count }} users found.1057- {% else %}1058- one user found.1059- {% endif %}1060-1061-*New in Jinja 1.1*: It's now possible to use the marker name as implicit1062-default:1063-1064-.. sourcecode:: jinja1065-1066- instead of this version:1067-1068- {% trans username=username %}Hello {{ username }}!{% endtrans %}1069-1070- you can now write this:1071-1072- {% trans username %}Hello {{ username }}!{% endtrans %}1073-1074-439 Bleeding Edge440 =============441 442 Here are some features documented that are new in the SVN version and might53 unmodified lines496 <li>[[6]]</li>497 </ul>498 499 .. _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.txtadded:docs/src/escaping.txt+71 added
1+=======================2+Whitespace and Escaping3+=======================4+5+This section of the documentation explains how to remove unused whitespace6+from the templates and embed raw Jinja syntax.7+8+Escaping9+========10+11+Sometimes you might want to add Jinja syntax elements into the template12+without executing them. In that case you have quite a few possibilities.13+14+For small parts this might be a good way:15+16+.. sourcecode:: jinja17+18+ {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}19+20+When you have multiple elements you can use the ``raw`` block:21+22+.. sourcecode:: jinja23+24+ {% 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 %}32+33+34+Whitespace35+==========36+37+If the Jinja environment was created with ``trim_blocks`` set to true the38+first newline after a template tag is removed automatically (php like39+processing).40+41+Starting with `Jinja 1.1` you can also handle some whitespace rules in the42+template. 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 remove44+the whitespaces after that block or before that block:45+46+.. sourcecode:: jinja47+48+ {% for item in seq -%}49+ {{ item }}50+ {%- endfor %}51+52+This will yield all elements without whitespace between them because they53+are automatically removed. This of course works for other tags too:54+55+.. sourcecode:: jinja56+57+ {% for user in userlist -%}58+ {{ user|e -}}59+ {% if not loop.last %},{% endif %}60+ {%- endfor %}61+62+Note that you must not use a whitespace between the tag and the minus sign:63+64+.. sourcecode:: jinja65+66+ valid:67+ {%- if foo -%}...{% endif %}68+69+ invalid:70+71+ {% - if foo - %}...{% endif %}modified:docs/src/index.txt+16 added-2 removed
45 unmodified lines46 developers.47 48 - **Template Designer Documentation**:49 50- - `Syntax Reference <designerdoc.txt>`_ - the designer documentation. Put51- this under your pillow.50+ - `Syntax Reference <designerdoc.txt>`_ - quick overview over the Jinja51+ syntax elements.52 53+ - `Template Inheritance <inheritance.txt>`_ - template inheritance howto.54+55+ - `Filters, Tests and Helper Functions <builtins.txt>`_ - list of filters56+ and test/helper functions.57+58+ - `Whitespace and Escaping <escaping.txt>`_ - how to escape markup and59+ control whitespace.60+61+ - `Scopes and Variable Behavior <scopes.txt>`_ - behavior of undefined62+ variables and scoping rules.63+64+ - `Template Internationalization <templatei18n.txt>`_ - how to internationalize65+ Jinja templates.66+67 - `Differences To Django <fromdjango.txt>`_ - coming from django? Then this68 document is for you.69 70 - `Designer Recipies <recipies.txt>`_ - various tips and tricks for designers.4 unmodified linesadded:docs/src/inheritance.txt+157 added
1+====================2+Template Inheritance3+====================4+5+The most powerful part of Jinja is template inheritance. Template inheritance6+allows you to build a base "skeleton" template that contains all the common7+elements of your site and defines **blocks** that child templates can override.8+9+Sounds complicated but is very basic. It's easiest to understand it by starting10+with an example.11+12+Base Template13+=============14+15+This template, which we'll call ``base.html``, defines a simple HTML skeleton16+document that you might use for a simple two-column page. It's the job of17+"child" templates to fill the empty blocks with content:18+19+.. sourcecode:: html+jinja20+21+ <!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>33+34+ <div id="footer">35+ {% block footer %}36+ © Copyright 2006 by <a href="http://mydomain.tld">myself</a>.37+ {% endblock %}38+ </div>39+ </body>40+41+In this example, the ``{% block %}`` tags define four blocks that child templates42+can fill in. All the `block` tag does is to tell the template engine that a43+child template may override those portions of the template.44+45+Child Template46+==============47+48+A child template might look like this:49+50+.. sourcecode:: html+jinja51+52+ {% extends "base.html" %}53+ {% block title %}Index{% endblock %}54+55+ {% 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 %}69+70+The ``{% extends %}`` tag is the key here. It tells the template engine that71+this template "extends" another template. When the template system evaluates72+this template, first it locates the parent.73+74+The filename of the template depends on the template loader. For example the75+``FileSystemLoader`` allows you to access other templates by giving the76+filename. You can access templates in subdirectories with an slash:77+78+.. sourcecode:: jinja79+80+ {% extends "layout/default.html" %}81+82+But this behavior can depend on the application using Jinja.83+84+Note that since the child template didn't define the ``footer`` block, the85+value from the parent template is used instead.86+87+.. admonition:: Note88+89+ 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.95+96+How Inheritance Works Internally97+================================98+99+Inheritance in Jinja is straighforward. If a template contains a100+``{% extends %}`` tag it's considered being a child template, otherwise it's101+a layout template. In a layout template you can place blocks basically102+everywhere. In a child template blocks can only be located either top level103+or inside of another block.104+105+Data outside of a block in a child template is executed before the layout106+template is rendered, thus you can use it to propagate data to the whole107+inheritance chain. Having a block in an invalid position you will receive108+an syntax error. Here some examples:109+110+**impossible**:111+112+ .. sourcecode:: jinja113+114+ {% extends 'master.html' %}115+ {% if some_condition %}116+ {% block body %}117+ ...118+ {% endblock %}119+ {% endif %}120+121+ This can't work because template inheritance works at translation /122+ compilation time not at template executation.123+124+**possible**:125+126+ .. sourcecode:: jinja127+128+ {% extends 'master.html' %}129+ {% block body %}130+ {% if some_condition %}131+ {% block myblock %}132+ ...133+ {% endblock %}134+ {% endblock %}135+ {% endblock %}136+137+ 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.140+141+Super Blocks142+============143+144+Starting with `Jinja 1.1` it's possible to render the contents of the parent145+block. By calling it you get the results of the parent block back. If you want146+to get the data of the parent you can give it an offset:147+148+.. sourcecode:: jinja149+150+ {{ super() }}151+ return the parent data152+153+ {{ super(1) }}154+ the same as above155+156+ {{ super(2) }}157+ return the data of the second parent blockmodified:docs/src/objects.txt+2 added-3 removed
88 unmodified lines89 class MyModel(...):90 91 # 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']96 97 def __init__(self, ...):98 ...31 unmodified linesadded:docs/src/scopes.txt+161 added
1+============================2+Scopes and Variable Behavior3+============================4+5+This section of the documentation covers the Jinja behavior regarding6+variable visibility.7+8+Scopes9+======10+11+Jinja has multiple scopes. A scope is something like a new transparent foil on12+a stack of foils. You can only write to the outermost foil but read all of them13+since you can look through them. If you remove the top foil all data on that14+foil disappears. Some tags in Jinja add a new layer to the stack. Currently15+these are `block`, `for`, `macro` and `filter`. This means that variables and16+other elements defined inside a macro, loop or some of the other tags listed17+above will be only available in that block. Here an example:18+19+.. sourcecode:: jinja20+21+ {% macro angryhello name %}22+ {% set angryname = name|upper %}23+ Hello {{ name }}. Hello {{ name }}!24+ HELLO {{ angryname }}!!!!!!11125+ {% endmacro %}26+27+The variable ``angryname`` just exists inside the macro, not outside it.28+29+Defined macros appear on the context as variables. Because of this, they are30+affected by the scoping too. A macro defined inside of a macro is just available31+in those two macros (the macro itself and the macro it's defined in).32+33+Template Globals34+================35+36+A special threatment exists for template code outside of visible blocks in37+child templates. This code will be executed **before** the layout template38+code. Thus it can be used to propagate values back to the layout template or39+import macros from templates for rendering.40+41+Such code can output data but it won't appear in the final rendering. So no42+additional whitespace will pollute the template.43+44+Because this code is executed before the actual layout template code it's45+possible that the layout code overrides some of those variables. Usually46+this is not a problem because of different variable names but it can be47+a problem if you plan to specify default values.48+49+In that case you have to test if the variable is not defined before setting50+it:51+52+.. sourcecode:: jinja53+54+ {% if not page_title %}55+ {% set page_title = 'Default Page Title' %}56+ {% endif %}57+58+You can of course also use the `|default` filter.59+60+.. admonition:: Explanation61+62+ This template stored as `a.html`:63+64+ .. sourcecode:: html+jinja65+66+ <title>{{ title|default('Untitled') }}</title>67+ <body>{% block body %}{% endblock %}68+69+ ...and this child template stored as `b.html`:70+71+ .. sourcecode:: html+jinja72+73+ {% extends 'a.html' %}74+ {% include 'macros.tmpl' %}75+ {% set title = 'My Page' %}76+ {% block body %}{{ wrap(42) }}{% endblock %}77+78+ ...and this code in `macros.tmpl`:79+80+ .. sourcecode:: html+jinja81+82+ {% macro wrap(text) %}83+ [{{ text }}]84+ {% endmacro %}85+86+ ..will translate to something with the same semantics as this (just87+ that the value is not stored in a variable):88+89+ .. sourcecode:: html+jinja90+91+ {% 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>101+102+.. admonition:: Note103+104+ 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.108+109+Undefined Variables110+===================111+112+If you have already worked with python you probably know about the fact that113+undefined variables raise an exception. This is different in Jinja. There is a114+special value called `undefined` that represents values that do not exist.115+116+Depending on the configuration it will behave different.117+118+In order to check if a value is defined you can use the `defined` test:119+120+.. sourcecode:: jinja121+122+ {{ myvariable is not defined }}123+ will return true if the variable does not exist.124+125+`SilentUndefined`:126+127+ 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.131+132+ In order to check if a value is defined you can use the `defined` test:133+134+ There are also some additional rules regarding this special value. Any135+ mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand136+ as result:137+138+ .. sourcecode:: jinja139+140+ {{ undefined + "foo" }}141+ returns "foo"142+143+ {{ undefined - 42 }}144+ returns 42. Note: not -42!145+146+ In any expression `undefined` evaluates to `false`. It has no length, all147+ attribute calls return undefined, calling too:148+149+ .. sourcecode:: jinja150+151+ {{ undefined.attribute().attribute_too[42] }}152+ still returns `undefined`.153+154+`ComplainingUndefined`:155+156+ 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.159+160+ 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+=============================2+Template Internationalization3+=============================4+5+If the application is configured for i18n, you can define translatable blocks6+for translators using the `trans` tag or the special underscore function:7+8+.. sourcecode:: jinja9+10+ {% trans %}11+ this is a translatable block12+ {% endtrans %}13+14+ {% trans "This is a translatable string" %}15+16+ {{ _("This is a translatable string") }}17+18+The latter one is useful if you want translatable arguments for filters etc.19+20+If you want to have plural forms too, use the `pluralize` block:21+22+.. sourcecode:: jinja23+24+ {% trans users=users %}25+ One user found.26+ {% pluralize %}27+ {{ users }} users found.28+ {% endtrans %}29+30+ {% 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 %}35+36+If you have multiple arguments, the first one is assumed to be the indicator (the37+number that is used to determine the correct singular or plural form. If you38+don't have the indicator variable on position 1 you have to tell the `pluralize`39+tag the correct variable name.40+41+Inside translatable blocks you cannot use blocks or expressions (however you can42+still use the ``raw`` block which will work as expected). The variable43+print syntax (``{{ variablename }}``) is the only way to insert the variables44+defined in the ``trans`` header. Filters must be applied in the header.45+46+.. admonition:: note47+48+ 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:52+53+ .. sourcecode:: jinja54+55+ {% if count != 1 %}56+ {{ count }} users found.57+ {% else %}58+ one user found.59+ {% endif %}60+61+*New in Jinja 1.1*: It's now possible to use the marker name as implicit62+default:63+64+.. sourcecode:: jinja65+66+ instead of this version:67+68+ {% trans username=username %}Hello {{ username }}!{% endtrans %}69+70+ you can now write this:71+72+ {% trans username %}Hello {{ username }}!{% endtrans %}