Skip to content
Myr

bootstrapped new documentation

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 c9705c2 · Browse files · 32 files+230 added−4027 removed
This commit

State

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

Diff stats

32 files+230 added−4027 removed

  • other:+230 added−4027 removed

32 files+230 added−4027 removed

deleted:docs/html/jinjabanner.pngbinary

A binary file, deleted.

deleted:docs/html/jinjalogo.pngbinary

A binary file, deleted.

deleted:docs/html/style.css-196 removed
1body {2 background-color: #333;3 margin: 0;4 padding: 0;5 font-family: 'Georgia', serif;6 font-size: 15px;7 color: #111;8}910#content {11 background-color: white;12 background-image: url(watermark.png);13 padding: 10px;14 margin: 25px;15 border: 4px solid #ddd;16}1718h1 {19 margin: 0;20 padding: 0;21 height: 80px;22 background-image: url(jinjabanner.png);23 background-repeat: no-repeat;24}2526h1 span {27 display: none;28}2930h2.subheading {31 margin: -55px 0 35px 200px;32 font-weight: normal;33 font-size: 30px;34 color: #444;35}3637h2.plain {38 margin: 0;39}4041#jinjalogo {42 background-image: url(jinjalogo.png);43 background-repeat: no-repeat;44 width: 400px;45 height: 160px;46}4748#contentwrapper {49 max-width: 700px;50 padding: 0 0 20px 18px;51}5253#contentwrapper h3,54#contentwrapper h3 a {55 color: #b41717;56 font-size: 26px;57 margin: 20px 0 0 -5px;58}5960#contentwrapper h4,61#contentwrapper h4 a {62 color: #b41717;63 font-size: 20px;64 margin: 20px 0 0 0;65}6667table.docutils {68 border-collapse: collapse;69 border: 2px solid #aaa;70 margin: 0.5em 1.5em 0.5em 1.5em;71}7273table.docutils td {74 padding: 2px;75 border: 1px solid #ddd;76}7778p, li, dd, dt, blockquote {79 color: #333;80}8182p {83 line-height: 150%;84 margin-bottom: 0;85 margin-top: 10px;86 text-align: justify;87}8889hr {90 border-top: 1px solid #ccc;91 border-bottom: 0;92 border-right: 0;93 border-left: 0;94 margin-bottom: 10px;95 margin-top: 20px;96}9798dl {99 margin-left: 10px;100}101102li, dt {103 margin-top: 5px;104}105106dt {107 font-weight: bold;108}109110th {111 text-align: left;112 padding: 3px;113 background-color: #f2f2f2;114}115116a {117 color: #b41717;118}119120a:hover {121 color: #444;122}123124pre {125 background-color: #f9f9f9;126 border-top: 1px solid #ccc;127 border-bottom: 1px solid #ccc;128 padding: 5px;129 font-size: 13px;130 font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;131}132133tt {134 font-size: 13px;135 font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;136 color: black;137 padding: 1px 2px 1px 2px;138 background-color: #f0f0f0;139}140141cite {142 /* abusing <cite>, it's generated by ReST for `x` */143 font-size: 13px;144 font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;145 font-weight: bold;146 font-style: normal;147}148149div.admonition {150 margin: 10px 0 10px 0;151 padding: 10px;152 border: 1px solid #ccc;153 background-color: #f8f8f8;154}155156div.admonition p.admonition-title {157 margin: -3px 0 5px 0;158 font-weight: bold;159 color: #b41717;160 font-size: 16px;161}162163div.admonition p {164 margin: 0 0 0 40px;165}166167#toc {168 margin: 0 -10px 10px 15px;169 padding: 10px;170 width: 200px;171 float: right;172 background-color: #f8f8f8;173 border: 1px solid #ccc;174 border-right: none;175}176177#toc h2 {178 font-size: 20px;179 margin: 0 0 10px 0;180 padding: 0;181 color: #444;182}183184#toc ul {185 margin: 0 0 0 30px;186 padding: 0;187}188189#toc ul + h2 {190 margin-top: 10px;191}192193#toc ul li {194 padding: 0;195 margin: 2px 0 2px 0;196}
deleted:docs/html/watermark.pngbinary

A binary file, deleted.

deleted:docs/src/altsyntax.txt-109 removed
1==================2Alternative Syntax3==================45Jinja allows some syntax customization for the block delimiters. Depending on6the Jinja release more or less combinations are possible. The idea of an7customizable syntax is that you can update existing templates from other8template engines and programming languages easier and that you can replace9the django like default delimiters which are not everybody's favorite.101112Configuring The Environment13===========================1415For syntax configuration there are six arguments in the environment which16are the first six for convenience. Thus those two snippets do the same:1718.. sourcecode:: python1920 env = Environment(21 block_start_string='{%',22 block_end_string='%}',23 variable_start_string='{{',24 variable_end_string='}}',25 comment_start_string='{#',26 comment_end_string='#}',27 )2829 env = Environment('{%', '%}', '{{', '}}', '{#', '#]')303132Ruby Like Syntax33----------------3435Here an example configuration for Ruby-like syntax:3637.. sourcecode:: python3839 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')4041An example template then looks like this:4243.. sourcecode:: rhtml4445 <%# example eruby like configuration for Jinja %>46 <ul>47 <% for item in seq %>48 <li><%= item %></li>49 <% end‭for %>50 </ul>515253SGML Comment Syntax54-------------------5556Here an example configuration that uses SGML comments to hide the57processing instructions. This can be useful if you work with an WYSIWYG58designer:5960.. sourcecode:: python6162 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')6364.. sourcecode:: html6566 <!--# example SGML comment configuration for Jinja -->67 <ul>68 <!-- for item in seq -->69 <li>${item}</li>70 <!-- endfor -->71 </ul>727374Parenthesis Balancing75---------------------7677Starting with Jinja 1.1 it's possible to use the block delimiter as a token78in the expression. That means that you can use small delimiters like single79braces or parenthesis. So if you want to have your variables to look like80``${expr}`` and you still want to use dicts in such expressions you need81Jinja 1.1 or higher.828384Block / Variable Tag Unification85================================8687If variable end and start tags are `None` or look the same as block tags and88you're running Jinja 1.1 or later the parser will switch into the89`no_comment_block` mode. In that mode it will try to match something as block90first and continue treating it as variable block if there is no known91directive for that name. Example:9293.. sourcecode:: python9495 env = Environment('{', '}', None, None, '{*', '*}')9697This now allows smarty like templates:9899.. sourcecode:: smarty100101 {* example smarty-like configuration for Jinja *}102 {if something == 42}103 Something is the answer to all questions and stuff like that.104 {else}105 Something is {something}.106 {endif}107108This feature however can cause strange looking templates because there is no109visible difference between blocks and variables.
deleted:docs/src/api.txt-315 removed
1=======================2Context and Environment3=======================45The two central objects in Jinja are the `Environment` and `Context`. Both6are designed to be subclassed by applications if they need to extend Jinja.78Environment9===========1011The initialization parameters are already covered in the `Quickstart`_ thus12not repeated here.1314But beside those configurable instance variables there are some functions used15in the template evaluation code you may want to override:1617**def** `parse` *(source, filename)*:1819 Parse the sourcecode and return the abstract syntax tree. This tree of20 nodes is used by the `translators`_ to convert the template into21 executable source- or bytecode.2223**def** `lex` *(source, filename)*:2425 Tokenize the given sourcecode and return a generator of tuples in the26 form ``(lineno, token, value)``. The filename is just used in the27 exceptions raised.28 29 **New in Jinja 1.1**3031**def** `from_string` *(source)*:3233 Load and parse a template source and translate it into eval-able Python34 code. This code is wrapped within a `Template` class that allows you to35 render it.3637**def** `get_template` *(name)*:3839 Load a template from a loader. If the template does not exist, you will40 get a `jinja.exceptions.TemplateNotFound` exception.4142**def** `to_unicode` *(self, value)*:4344 Called to convert variables to unicode. Per default this checks if the45 value is already unicode. If not it's converted to unicode using the46 charset defined on the environment.4748 Also `None` is converted into an empty string per default.4950**def** `get_translator` *(self, context)*:5152 Return the translator used for i18n. A translator is an object that53 provides the two functions ``gettext(string)`` and54 ``ngettext(singular, plural, n)``. Both of those functions have to55 behave like the `ugettext` and `nugettext` functions described in the56 python `gettext documentation`_.5758 If you don't provide a translator a default one is used to switch59 between singular and plural forms.6061 Have a look at the `i18n`_ section for more information.6263**def** `get_translations` *(self, name)*:6465 Get the translations for the template `name`. Only works if a loader66 is present. See the `i18n`_ section for more details.6768**def** `get_translations_for_string` *(self, string)*:6970 Get the translations for the string `string`. This works also if no71 loader is present and can be used to lookup translation strings from72 templates that are loaded from dynamic resources like databases.7374**def** `apply_filters` *(self, value, context, filters)*:7576 Now this function is a bit tricky and you usually don't have to override77 it. It's used to apply filters on a value. The Jinja expression78 ``{{ foo|escape|replace('a', 'b') }}`` calls the function with the79 value of `foo` as first parameter, the current context as second and80 a list of filters as third. The list looks like this:8182 .. sourcecode:: python8384 [('escape', ()), ('replace', (u'a', u'b'))]8586 As you can see the filter `escape` is called without arguments whereas87 `replace` is called with the two literal strings ``a`` and ``b``, both88 unicode. The filters for the names are stored on ``self.filters`` in a89 dict. Missing filters should raise a `FilterNotFound` exception.9091 **Warning** this is a Jinja internal method. The actual implementation92 and function signature might change.9394**def** `perform_test` *(self, context, testname, args, value, invert)*:9596 Like `apply_filters` you usually don't override this one. It's the97 callback function for tests (``foo is bar`` / ``foo is not bar``).9899 The first parameter is the current contex, the second the name of100 the test to perform. the third a tuple of arguments, the fourth is101 the value to test. The last one is `True` if the test was performed102 with the `is not` operator, `False` if with the `is` operator.103104 Missing tests should raise a `TestNotFound` exception.105106 **Warning** this is a Jinja internal method. The actual implementation107 and function signature might change.108109**def** `get_attribute` *(self, obj, attribute)*:110111 Get `attribute` from the object provided. The default implementation112 performs security tests.113114 **Warning** this is a Jinja internal method. The actual implementation115 and function signature might change.116117**def** `get_attributes` *(self, obj, attributes)*:118119 Get some attributes from the object. If `attributes` is an empty120 sequence the object itself is returned unchanged.121122**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:123 124 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and125 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`126 is not `None` you have to add it to the arguments, if `dyn_kwargs` is127 not `None` you have to update the `kwargs` with it.128129 The default implementation performs some security checks.130131 **Warning** this is a Jinja internal method. The actual implementation132 and function signature might change.133134**def** `call_function_simple` *(self, f, context)*:135136 Like `call_function` but without arguments.137138 **Warning** this is a Jinja internal method. The actual implementation139 and function signature might change.140141**def** `finish_var` *(self, value, ctx)*:142143 Postprocess a variable before it's sent to the template.144145 **Warning** this is a Jinja internal method. The actual implementation146 and function signature might change.147 148.. admonition:: Note149150 The Enviornment class is defined in `jinja.environment.Environment`151 but imported into the `jinja` package because it's often used.152153Context154=======155156Jinja wraps the variables passed to the template in a special class called a157context. This context supports variables on multiple layers and lazy (deferred)158objects. Often your application has a request object, database connection159object or something similar you want to access in filters, functions etc.160161The default context object is defined in `jinja.datastructure`. If you want162to provide your own context object always subclass the default one. This163ensures that the class continues working after Jinja upgrades.164165Beacause of that you can easily subclass a context to add additional variables166or to change the way it behaves.167168**def** `pop` *(self)*:169170 Pop the outermost layer and return it.171172**def** `push` *(self, data=None)*:173174 Push a dict to the stack or an empty layer.175176 Has to return the pushed object.177178**def** `to_dict` *(self)*:179180 Flatten the context and convert it into a dict.181182**def** `__getitem__` *(self, name)*:183184 Resolve an item. Per default this also resolves `Deferred` objects.185186**def** `__setitem__` *(self, name, value)*:187188 Set an item in the outermost layer.189190**def** `__delitem__` *(self, name)*:191192 Delete an item in the outermost layer. Do not raise exceptions if193 the value does not exist.194195**def** `__contains__` *(self, name)*:196197 Return `True` if `name` exists in the context.198199**attribute** `cache`:200201 The cache is a dict which can be used by filters, test functions202 and global objects to cache data. It's also used by the environment203 to cache often used tests and filters.204205**attribute** `translate_func`:206207 This property is created on first access and returns a translation208 function used by the rendering process to translate strings with the209 translator defined on the environment.210211.. admonition:: Note212213 The context uses a stack of dicts internally to represent the214 layers of variables. It contains at least 3 levels available on215 the context with some attributes. Those are:216217 `globals`:218 219 The reference to the global namespace of the environment.220 It's the lowest namespace on the stack and thus immutable221222 `initial`:223224 The initial namespace. Contains the values passed to the225 context in the render function. It also contains the resolved226 deferred values for bot the `initial` and the `globals`227 namespace.228229 `current`:230231 The reference to the current active namespace. When the232 context is initialized this automatically points to an233 empty namespace.234235 The number of layers on the stack are theoretically unlimited.236 Some elements in the template language like loops, blocks,237 macros and others push and pop the layer on entering and leaving238 the section.239240 This is done in order to keep the namespace clean.241242 Note that since Jinja 1.1 the context object is a subclass of the243 `BaseContext`, a much simpler class that just implements a stack244 like namespace for python. If the `_speedups` extension was245 compiled for jinja the base class will be246 `jinja._speedups.BaseContext` otherwise `jinja._native.BaseContext`.247248 Since you cannot reproduce completely the same semantics in python249 and the C API there are some things you should keep in mind:250251 - The `stack` attribute of the context maps to the real layers252 on the stack, thus you can modify the items but the list as253 such is meant to be read only.254255 - `globals`, `current` and `initial` are read only attributes that256 map to layers on the stack which you can of course modify.257258259Exceptions260==========261262During parsing and evaluation Jinja raises a couple of Jinja specific263exceptions. All of those exceptions are defined in the `jinja.exceptions`264module and are subclasses of the `TemplateError` class defined there.265266Here a list of exceptions that could occur:267268`SecurityException`:269270 An exception that is raised if the template tried to access something271 it should not access. In the default configuration this exception272 will get caught in the Jinja rendering process and silenced.273274 If however the environment is configured to not silently fail it275 could happen that this exception reaches the application.276277`FilterNotFound`:278279 Raised if the template tried to apply a filter that does not exist.280 Since this exception is a subclass of `KeyError` too you can catch281 it this way too.282283`FilterArgumentError`:284285 Raised if the filter received an argument that it couldn't handle.286 It's a subclass of `TypeError` too so you can catch it this way too.287288`TestNotFound`:289290 Raised if the template tried to perform a test that does not exist.291 Since this exception is a subclass of `KeyError` too you can catch292 it this way too.293294`TestArgumentError`:295296 Raised if a test function received an argument that it couldn't handle.297 It's a subclass of `TypeError` too so you can catch it this way too.298299`TemplateNotFound`:300301 Raised if a template does not exist. Subclass of `IOError` too.302303`TemplateSyntaxError`:304305 Subclass of `SyntaxError` and used to indicate an syntax error.306307`TemplateRuntimeError`:308309 Generic runtime error exception which can occour at various places.310311312.. _i18n: i18n.txt313.. _translators: translators.txt314.. _Quickstart: devintro.txt315.. _gettext documentation: http://docs.python.org/lib/module-gettext.html
deleted:docs/src/builtins.txt-228 removed
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 *Jinja 1.0 and 1.1 notice*3132 The filter operator has a pretty low priority in Jinja 1.0 and 1.1. If you33 want to add fitered values you have to put them into parentheses. The same34 applies if you want to access attributes or return values:3536 .. sourcecode:: jinja3738 correct:39 {{ (foo|filter) + (bar|filter) }}40 wrong:41 {{ foo|filter + bar|filter }}4243 correct:44 {{ (foo|filter).attribute }}45 wrong:46 {{ foo|filter.attribute }}4748 This changed in Jinja 1.2, from that version one the filter operator has49 the highest priority so you can do ``foo|filter + bar|filter``.5051*new in Jinja 1.1*:5253Because the application can provide additional filters you can get a documentation54of all the provided filters by calling ``debug.filters()``:5556.. sourcecode:: jinja5758 {{ debug.filters() }}59 -> returns a plain text representation of all the filters6061 {{ debug.filters(False) }}62 -> same as above but without the builtin ones.6364Tests65=====6667You can use the `is` operator to perform tests on a value:6869.. sourcecode:: jinja7071 {{ 42 is numeric }} -> true72 {{ "foobar" is numeric }} -> false73 {{ 'FOO' is upper }} -> true7475These tests are especially useful when used in `if` conditions.7677[[list_of_tests]]7879*new in Jinja 1.1*:8081Because the application can provide additional tests you can get a documentation82of all the provided tests by calling ``debug.tests()``:8384.. sourcecode:: jinja8586 {{ debug.tests() }}87 -> returns a plain text representation of all the tests8889 {{ debug.tests(False) }}90 -> same as above but without the builtin ones.9192*new in Jinja 1.2*:9394If a test function expects one or no argument you can leave out the parentheses.95Previously this was only possible for text functions without arguments:9697.. sourcecode:: jinja9899 {{ foo is matching @/\s+/ }}100 is the same as101 {{ foo is matching(@/\s+/) }}102103104Global Functions105================106107Test functions and filter functions live in their own namespace. Global108functions not. They behave like normal objects in the context. Beside the109functions added by the application or framewhere there are two functions110available per default:111112`range`113 114 Works like the python `range function`_ just that it doesn't support115 ranges greater than ``1000000``.116117`debug`118119 Function that outputs the contents of the context.120121`lipsum`122123 Generate some paragraphs of random text:124125 .. sourcecode:: jinja126127 {{ lipsum(5) }}128 five html paragraphs129130 {{ lipsum(2, False) }}131 two ascii only paragraphs132133 Per default a paragraph is between 20 and 100 words long. You can134 override this default with the third and fourth parameter:135136 .. sourcecode:: jinja137138 {{ lipsum(10, True, 50, 200) }}139 generate 10 HTML paragraphs between 50 and 200 words.140141 *new in Jinja 1.1*142143`watchchanges`144145 Jinja does not provide an django like ``{% ifchanged %}`` tag. As146 replacement for this tag there is a special function in the namespace147 called `watchchanges`.148149 You can use it like this:150151 .. sourcecode:: html+jinja152153 {% for changed, article in watchchanges(articles, 'date', 'day') %}154 {% if changed %}<h3>{{ articles.date.day }}</h3>{% endif %}155 <h4>{{ article.title|e }}</h4>156 <p>{{ article.body|e }}</p>157 {% endif %}158159 For each iteration `watchchanges` will check the given attribute. If it160 changed to the former iteration the first yielded item (in this example161 it's called `changed`) will be `true`, else `false`.162163 In this example `articles` is a list of articles for the template with164 an attribute called `date.day` which represents the current day. To only165 add a new day headline if the day has changed `watchchanges` is now told166 to check `articles.date.days`.167168 If you want to observe more than one attribute you can provide pairs:169170 .. sourcecode:: html+jinja171172 {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}173 ...174 {% endfor %}175176 Note that if you want to watch two first level attributes you have to177 either use the list syntax `[]` or add a colon:178179 .. sourcecode:: html+jinja180181 {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}182 ...183 {% endfor %}184185 otherwise Jinja cannot differ between a pair of parentheses to group186 expressions or the sequence syntax.187188 If you don't provide any arguments the value of the variable itself189 is checked.190191 *new in Jinja 1.1*192193`rendertemplate`194195 Loads and renders a template with a copy of the current context. This works196 in many situations like the ``{% include %}`` tag, just that it does not197 include a template and merges it into the template structure but renders198 it completely independent and returns the rendered data as string.199200 *new in Jinja 1.1*201202203Global Constants204================205206Jinja provides some special variables which cannot be overridden in templates.207Those are not affected by the variable lookup:208209 `_`, `true`, `false`, `none`, `undefined`210211You cannot use those names for your own variables or macros. It's however no212problem to have blocks with that name.213214**Notice** due to a bug in Jinja 1.0 it was possible to override `_`, `true`,215`false`, `none` and `undefined` from the template by either using `{% set %}`216or in a for loop. While overriding `true`, `false` etc just caused nothing217overriding the translation marker `_` would crash the translation interface.218If you want to use `_` for unpacking in for loops (eg. skipping items) you219have to give it a proper name:220221.. sourcecode:: jinja222223 {% for key, ignore in mydict|dictsort %}224 {{ key|e }}225 {% endfor %}226227228.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000
deleted:docs/src/changelog.txt-1 removed
1[[changelog]]
deleted:docs/src/debugging.txt-32 removed
1===================2Debugging Templates3===================45In order to keep templates debuggable you have to do some additional work on6the application side. The traceback module that comes with python currently7does not support the `__loader__` hook which is used by Jinja to provide8templates. Although the import system was implemented three Python versions9ago the default traceback system still doesn't support it.1011However most of the extended web development traceback modules have support12for `__loader__`. Either directly or via the linecache module:1314- `Werkzeug Debugging Middleware`_15- `Django`_16- `cgitb`_17- `EvalException`_1819To enable debugging you have to use one of those debugging systems or20implement your own one with support for `__loader__`.2122The python implementation of the jinja debugger can only translate the first23exception in a traceback which can lead to problematic results. If you have24the extended debugger c extension compiled (default on unix systems but only25available on Windows if you have a VisualStudio 2003 installation) all frames26in the traceback will point to the correct linenumbers of the templates.272829.. _Werkzeug Debugging Middleware: http://werkzeug.pocoo.org/30.. _Django: http://www.djangoproject.com/31.. _cgitb: http://docs.python.org/lib/module-cgitb.html32.. _EvalException: http://pythonpaste.org/module-paste.evalexception.html
deleted:docs/src/designerdoc.txt-565 removed
1======================2Designer Documentation3======================45This part of the Jinja documentaton is meant for template designers.67Basics8======910The Jinja template language is designed to strike a balance between content11and application logic. Nevertheless you can use a python like statement12language. You don't have to know how Python works to create Jinja templates,13but if you know it you can use some additional statements you may know from14Python.1516Here is a small example template:1718.. sourcecode:: html+jinja1920 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"21 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">22 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">23 <head>24 <title>My Webpage</title>25 </head>26 <body>27 <ul id="navigation">28 {% for item in navigation %}29 <li><a href="{{ item.href|e }}">{{ item.caption|e }}</a></li>30 {% endfor %}31 </ul>3233 <h1>My Webpage</h1>34 {{ variable }}35 </body>36 </html>3738This covers the default settings. The application developer might have changed39the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar. This40documentation just covers the default values.4142A variable looks like ``{{ foobar }}`` where foobar is the variable name. Inside43of statements (``{% some content here %}``) variables are just normal names44without the braces around it. In fact ``{{ foobar }}`` is just an alias for45the statement ``{% print foobar %}``.4647Variables are coming from the context provided by the application. Normally there48should be a documentation regarding the context contents but if you want to know49the content of the current context, you can add this to your template:5051.. sourcecode:: html+jinja5253 <pre>{{ debug()|e }}</pre>5455A context isn't flat which means that each variable can has subvariables, as long56as it is representable as python data structure. You can access attributes of57a variable using the dot and bracket operators. The following examples show58this:5960.. sourcecode:: jinja6162 {{ user.username }}63 is the same as64 {{ user['username'] }}65 you can also use a variable to access an attribute:66 {{ users[current_user].username }}67 If you have numerical indices you have to use the [] syntax:68 {{ users[0].username }}6970*new in Jinja 1.2*: You can now use django like attributes for integer71indices. Thus ``{{ foo.0 }}`` is equivalent to ``{{ foo[0] }}``.727374Loops75=====7677To iterate over a sequence, you can use the `for` loop. It basically looks like a78normal Python `for` loop and works pretty much the same:7980.. sourcecode:: html+jinja8182 <h1>Members</h1>83 <ul>84 {% for user in users %}85 <li>{{ loop.index }} / {{ loop.length }} - {{ user.username|escape }}</li>86 {% else %}87 <li><em>no users found</em></li>88 {% endfor %}89 </ul>9091*Important* Contrary to Python is the optional `else` block only92executed if there was no iteration because the sequence was empty.9394Inside of a `for` loop block you can access some special variables:9596+----------------------+----------------------------------------+97| Variable | Description |98+======================+========================================+99| `loop.index` | The current iteration of the loop. |100+----------------------+----------------------------------------+101| `loop.index0` | The current iteration of the loop, |102| | starting counting by 0. |103+----------------------+----------------------------------------+104| `loop.revindex` | The number of iterations from the end |105| | of the loop. |106+----------------------+----------------------------------------+107| `loop.revindex0` | The number of iterations from the end |108| | of the loop, starting counting by 0. |109+----------------------+----------------------------------------+110| `loop.first` | True if first iteration. |111+----------------------+----------------------------------------+112| `loop.last` | True if last iteration. |113+----------------------+----------------------------------------+114| `loop.even` | True if current iteration is even. |115+----------------------+----------------------------------------+116| `loop.odd` | True if current iteration is odd. |117+----------------------+----------------------------------------+118| `loop.length` | Total number of items in the sequence. |119+----------------------+----------------------------------------+120| `loop.parent` | The context of the parent loop. |121+----------------------+----------------------------------------+122123Loops also support recursion. Let's assume you have a sitemap where each item124might have a number of child items. A template for that could look like this:125126.. sourcecode:: html+jinja127128 <h1>Sitemap129 <ul id="sitemap">130 {% for item in sitemap recursive %}131 <li><a href="{{ item.url|e }}">{{ item.title|e }}</a>132 {% if item.children %}<ul>{{ loop(item.children) }}</ul>{% endif %}</li>133 {% endfor %}134 </ul>135136What happens here? Basically the first thing that is different to a normal137loop is the additional ``recursive`` modifier in the `for`-loop declaration.138It tells the template engine that we want recursion. If recursion is enabled139the special `loop` variable is callable. If you call it with a sequence it will140automatically render the loop at that position with the new sequence as argument.141142Cycling143=======144145Sometimes you might want to have different text snippets for each row in a list,146for example to have alternating row colors. You can easily do this by using the147``{% cycle %}`` tag:148149.. sourcecode:: html+jinja150151 <ul id="messages">152 {% for message in messages %}153 <li class="{% cycle 'row1', 'row2' %}">{{ message|e }}</li>154 {% endfor %}155 </ul>156157Each time Jinja encounters a `cycle` tag it will cycle through the list158of given items and return the next one. If you pass it one item jinja assumes159that this item is a sequence from the context and uses this:160161.. sourcecode:: html+jinja162163 <li style="color: {% cycle rowcolors %}">...</li>164165Conditions166==========167168Jinja supports Python-like `if` / `elif` / `else` constructs:169170.. sourcecode:: jinja171172 {% if user.active %}173 user {{ user.name|e }} is active.174 {% elif user.deleted %}175 user {{ user.name|e }} was deleted some time ago.176 {% else %}177 i don't know what's wrong with {{ user.username|e }}178 {% endif %}179180If the user is active the first block is rendered. If not and the user was181deleted the second one, in all other cases the third one.182183You can also use comparison operators:184185.. sourcecode:: html+jinja186187 {% if amount < 0 %}188 <span style="color: red">{{ amount }}</span>189 {% else %}190 <span style="color: black">{{ amount }}</span>191 {% endif %}192193.. admonition:: Note194195 Of course you can use `or` / `and` and parentheses to create more complex196 conditions, but usually the logic is already handled in the application and197 you don't have to create such complex constructs in the template code. However198 in some situations it might be a good thing to have the abilities to create199 them.200201Literals202========203204For most of the builtin python types, literals exist in Jinja. The following205table shows which syntax elements are supported:206207 ======================= ===================================================208 ``"text" / 'text'`` work like python's unicode literals (u'text').209 ``42`` integer literls.210 ``42.0`` float literals (exponents are not supported and211 before and after the dot digits must be present)212 ``[1, 'two', none]`` list literal213 ``(), (1,), (1, 2)`` tuple literals. (tuples work like lists but consume214 less memory and are not modifyable.)215 ``{'foo': 'bar'}`` dictionary literal216 ``@/expr/flags`` regular expression literals. ``@/expr/flags`` is217 equivalent to ``re.compile('(?flags)expr')`` in218 python.219 ``@(1, 2, 3)`` set literal. ``@(1, 2, 3)`` in Jinja is is equal to220 ``set([1, 2, 3])`` in python.221 ``true / false`` corresponds to `True` and `False` in python.222 ``none`` corresponds to `None` in python.223 ``undefined`` special Jinja undefined singleton.224 ======================= ===================================================225226.. admonition:: Common Pitfalls227228 Keep in mind that Jinja literals, keywords and functions are all lowercase.229 If you're used to Python you probably tried to write `True` which evaluates230 to undefined because it simply does not exist. The correct name for the231 true value is just `true` (lowercase).232 233234Operators235=========236237Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can238can use expressions. In expressions you can use any of the following operators:239240 ======= ===================================================================241 ``+`` add the right operand to the left one.242 ``{{ 1 + 2 }}`` would return ``3``.243 ``-`` subtract the right operand from the left one.244 ``{{ 1 - 1 }}`` would return ``0``.245 ``/`` divide the left operand by the right one.246 ``{{ 1 / 2 }}`` would return ``0.5``.247 ``//`` divide the left operand by the right one and return a truncated248 integer result: ``{{ 20 // 7 }}`` is ``2``.249 *added in Jinja 1.1*250 ``~`` string concatenate a value with another one. ``{{ foo ~ bar }}``251 is equivalent to ``{{ foo|string + bar|string }}``. *added in252 Jinja 1.1*253 ``*`` multiply the left operand with the right one.254 ``{{ 2 * 2 }}`` would return ``4``.255 ``**`` raise the left operand to the power of the right256 operand. ``{{ 2**3 }}`` would return ``8``.257 ``%`` calculate the remainder of an integer division between the258 left and right operand: ``{{ 11 % 7 }}`` is ``4``.259 ``in`` perform sequence membership test. ``{{ 1 in [1,2,3] }}`` would260 return true.261 ``is`` perform a test on the value. See the section about262 tests for more information.263 ``|`` apply a filter on the value. See the section about264 filters for more information.265 ``and`` return true if the left and the right operand is true.266 ``or`` return true if the left or the right operand is true.267 ``not`` negate a statement (see below)268 ``()`` call a callable: ``{{ user.get_username() }}``. Inside of the269 parentheses you can use variables: ``{{ user.get(username) }}``.270 ======= ===================================================================271272Note that there is no support for any bit operations or something similar.273274* special note regarding `not`: The `is` and `in` operators support negation275 using an infix notation too: ``foo is not bar`` and ``foo not in bar``276 instead of ``not foo is bar`` and ``not foo in bar``. All other expressions277 require a prefix notation: ``not (foo and bar)``.278279280With Jinja 1.2 onwards it's possible to replace basic if/else blocks with the281inline `if` / `else` expression. The following two examples evaluate to the282same:283284.. sourcecode:: jinja285286 {{ "something" if expr else "otherthing" }}287288 {% if expr %}something{% else %}otherthing{% endif %}289290291Boolean Values292==============293294In If-Conditions Jinja performs a boolean check. All empty values (eg: empty295lists ``[]``, empty dicts ``{}`` etc) evaluate to `false`. Numbers that are296equal to `0`/`0.00` are considered `false` too. The boolean value of other297objects depends on the behavior the application developer gave it. Usually298items are `true`.299300Here some examples that should explain it:301302.. sourcecode:: jinja303304 {% if [] %}305 will always be false because it's an empty list306307 {% if {} %}308 false too.309310 {% if ['foo'] %}311 this is true. Because the list is not empty.312313 {% if "foobar" %}314 this is also true because the string is not empty.315316Slicing317=======318319Some objects support slicing operations. For example lists:320321.. sourcecode:: jinja322323 {% for item in items[:5] %}324 This will only iterate over the first 5 items of the list325326 {% for item in items[5:10] %}327 This will only iterate from item 5 to 10.328329 {% for item in items[:10:2] %}330 This will only yield items from start to ten and only returing331 even items.332333For more informations about slicing have a look at the `slicing chapter`_334in the "Dive into Python" e-book.335336Macros337======338339If you want to use a partial template in more than one place, you might want to340create a macro from it:341342.. sourcecode:: html+jinja343344 {% macro show_user user %}345 <h1>{{ user.name|e }}</h1>346 <div class="text">347 {{ user.description }}348 </div>349 {% endmacro %}350351Now you can use it from everywhere in the code by passing it an item:352353.. sourcecode:: jinja354 355 {% for user in users %}356 {{ show_user(user) }}357 {% endfor %}358359You can also specify more than one value:360361.. sourcecode:: html+jinja362363 {% macro show_dialog title, text %}364 <div class="dialog">365 <h1>{{ title|e }}</h1>366 <div class="text">{{ text|e }}</div>367 </div>368 {% endmacro %}369370 {{ show_dialog('Warning', 'something went wrong i guess') }}371372*Improvements in Jinja 1.1*:373374 Starting with Jinja 1.1 it's possible to use optional parentheses375 around the macro arguments:376377 .. sourcecode:: html+jinja378379 {% macro foo(a, b) %}380 ...381 {% endmacro %}382383 Additionally extra arguments passed to the macro end up in the384 special variable `varargs`. So you can have a macro like this:385386 .. sourcecode:: html+jinja387388 {% macro make_list() %}389 {% if varargs %}390 <ul>391 {% for item in varargs %}392 <li>{{ item|e }}</li>393 {% endfor %}394 </ul>395 {% endif %}396 {% endmacro %}397398 {{ make_list("John", "Jane", "Marcus", "Heinrich") }}399400 If a macro parameter is called `varargs` the additional extra401 arguments are not accessible.402403For information regarding the visibility of macros have a look at the404`Scopes and Variable Behavior`_ section.405406407Extended Macro Call408===================409410*new in Jinja 1.1*411412Jinja 1.1 adds a new special tag that you can use to pass some evaluable413template code to a macro. Here an example macro that uses the features of414the ``{% call %}`` tag:415416.. sourcecode:: html+jinja417418 {% macro dialog title %}419 <div class="dialog">420 <h3>{{ title }}</h3>421 <div class="text">422 {{ caller() }}423 </div>424 </div>425 {% endmacro %}426427Called the normal way `caller` will be undefined, but if you call it428using the new `{% call %}` tag you can pass it some data:429430.. sourcecode:: html+jinja431432 {% call dialog('Hello World') %}433 This is an example dialog434 {% endcall %}435436Now the data wrapped will be inserted where you put the `caller` call.437438If you pass `caller()` some keyword arguments those are added to the439namespace of the wrapped template data:440441.. sourcecode:: html+jinja442443 {% macro makelist items %}444 <ul>445 {%- for item in items %}446 <li>{{ caller(item=item) }}</li>447 {%- endfor %}448 </ul>449 {%- endmacro %}450451 {% call makelist([1, 2, 3, 4, 5, 6]) -%}452 [[{{ item }}]]453 {%- endcall %}454455This will then produce this output:456457.. sourcecode:: html458459 <ul>460 <li>[[1]]</li>461 <li>[[2]]</li>462 <li>[[3]]</li>463 <li>[[4]]</li>464 <li>[[5]]</li>465 <li>[[6]]</li>466 </ul>467468469Template Inclusion470==================471472You can load another template at a given position using ``{% include %}``.473Usually it's a better idea to use inheritance but if you for example want to474load macros, `include` works better than `extends`:475476.. sourcecode:: jinja477478 {% include "myhelpers.html" %}479 {{ my_helper("foo") }}480481If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now482use it from the template as shown above.483484Please keep in mind that include does not render the template indenpendently485but includes the processing instructions into the current template. Thus if the486included template contains a ``{% extends %}`` tag it also affects the current487template.488489This is intended because it makes it possible to include macros from other490templates.491492*new in Jinja 1.1* you can now render an included template to a string that is493evaluated in an indepdendent environment by calling `rendertemplate`. See the494documentation for this function in the `builtins`_ documentation.495496497Filtering Blocks498================499500Sometimes it could be a good idea to filter a complete block of text. For501example, if you want to escape some html code:502503.. sourcecode:: jinja504505 {% filter escape %}506 <html>507 <code>goes here</code>508 </html>509 {% endfilter %}510511Of course you can chain filters too:512513.. sourcecode:: jinja514515 {% filter lower|escape %}516 <B>SOME TEXT</B>517 {% endfilter %}518519returns ``"&lt;b&gt;some text&lt;/b&gt;"``.520521522Defining Variables523==================524525You can also define variables in the namespace using the ``{% set %}`` tag:526527.. sourcecode:: jinja528529 {% set foo = 'foobar' %}530 {{ foo }}531532This should ouput ``foobar``.533534For information regarding the visibility of variables have a look at the535`Scopes and Variable Behavior`_ section.536537538Reserved Keywords539=================540541Jinja has some keywords you cannot use a variable names. This limitation542exists to make templates look coherent. Syntax highlighters won't mess things543up and you won't have the situation that some names work depending on the544context.545546The following keywords exist and cannot be used as identifiers:547548 `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,549 `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,550 `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,551 `print`, `raw`, `recursive`, `set`, `trans`, `call`, `endcall`552553If you want to use such a name you have to prefix or suffix it or use554alternative names:555556.. sourcecode:: jinja557558 {% for macro_ in macros %}559 {{ macro_('foo') }}560 {% endfor %}561562563.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice564.. _Scopes and Variable Behavior: scopes.txt565.. _builtins: builtins.txt
deleted:docs/src/devintro.txt-190 removed
1====================2Developer Quickstart3====================45This part of the documentation shows you how to embed Jinja into your6application.78Starting Up9===========1011Here the quickest way to create a template from a string and render it:1213.. sourcecode:: python1415 from jinja import Environment16 env = Environment()17 tmpl = env.from_string('Hello {{ name }}!')18 print tmpl.render(name='John Doe')1920This example should output the following string after execution::2122 Hello John Doe!2324If you receive an error, check if you have a typo in your code. If not, have25a look at the `installation`_ page for troubleshooting.2627Basically the important method on a template is the `render` method. It28takes either a dict or keyword arguments. All keyword arguments appear29in the template as variables.3031So these two snippets do the same:3233.. sourcecode:: python3435 tmpl.render(36 knights='we say nih',37 spam='and eggs'38 )3940.. sourcecode:: python4142 tmpl.render({43 'knights': 'we say nih',44 'spam': 'and eggs'45 })4647The Environment48===============4950[[environment_doc]]5152The environment provides the following useful functions and properties in53addition to the initialization values:5455=========================== ==================================================56``parse(source, filename)`` Parse the sourcecode and return the abstract57 syntax tree. This tree of nodes is used by the58 `translators`_ to convert the template into59 executable source- or bytecode.60``lex(source, filename)`` Tokenize the given sourcecode and return a61 generator of tuples in the form62 ``(lineno, token, value)``. The filename is just63 used in the exceptions raised.64 **New in Jinja 1.1**65``from_string(source)`` Load and parse a template source and translate it66 into eval-able Python code. This code is wrapped67 within a `Template` class that allows you to68 render it.69``get_template(name)`` Load a template from a loader. If the template70 does not exist, you will get a `TemplateNotFound`71 exception.72=========================== ==================================================7374There are also some internal functions on the environment used by the template75evaluation code to keep it sandboxed.7677Undefined Values78================7980If a template designer tries to access a not defined value the return value81will be the `undefined_singleton` specified in the environment. The default82one is the `SilentUndefined` which fails in no case. Additionally there is83a special undefined type called the `ComplainingUndefined` which is located84in the `jinja.datastructure` module. It will raise exceptions when compared85with other types, or when rendered.8687Theoretically you can provide your own singleton by subclassing88`AbstractUndefindedType` and creating an instance of it using `make_undefined`89(both located in `jinja.datastructure`) but those two types should cover90the basic use cases. The `Undefined` object in that module exists for91backwards compatibility and is an alias for `SilentUndefined`.9293To create your own undefined singleton do something like this:9495.. sourcecode:: jinja9697 from jinja.datastructure import AbstractUndefinedType, make_undefined9899 class MyUndefinedType(AbstractUndefindedType):100 __slots__ = ()101102 def __iter__(self):103 return iter(int, 0)104105 def __reduce__(self):106 return 'MyUndefined'107108 MyUndefined = make_undefined(MyUndefinedType)109110The only thing you have to do is to override `__reduce__` so that it returns111the name of the singleton instance and create the instance using112`make_undefined`. Everything else is up to you. Note that currently attributes113on undefined objects are available in the Jinja layer too which however114will change in one of the next Jinja versions. So if you put a `foo` attribute115on your undefined singleton you will be able to do ``{{ undefined.foo }}``116by now but certainly not in the future.117118This limitation currently exists because undefined is treated as normal object119and thus affected by normal getattr calls.120121122Automatic Escaping123==================124125Jinja provides a way for automatic escaping, but we do not recommend using it.126Because Jinja was designed as multi purpose template engine there are some127issues with automatic escaping. For example filters don't deal with markup128data. Also you can easily bypass the automatic escaping so it's not something129you can expect to "just work". Also there is a huge overhead when escaping130everything.131132The best idea is to think about which data already contains html, which will133probably contain (eg: every user input, etc) etc. And live with self escaping.134135That's usually a much better idea.136137138Loading Templates From Files139============================140141Loading templates from a string is always a bad idea. It doesn't allow template142inheritance and is also slow since it parses and compiles the template again143and again whereas loaders can cache the template code.144145All you have to do is to define a loader and use the `get_template` function.146147.. sourcecode:: python148149 from jinja import Environment, FileSystemLoader150 env = Environment(loader=FileSystemLoader('templates'))151 tmpl = env.get_template('index.html')152 print tmpl.render(name='John Doe')153154This tells jinja to look for templates in the ``templates`` folder. It's a155better idea to use an absolute path here though. For a list of supported156loaders or how to write your own, head over to the `loader`_ documentation.157158Adding Filters159==============160161If you want to add additional filters to the environment, the best way is to162modify the ``filters`` attribute and not to pass a dict to the environment.163If you pass it a dict it will not include the default filters!164165.. sourcecode:: python166167 from mylib import my_cool_filter168 env.filters['mycoolfilter'] = my_cool_filter169170Writing filter functions is explained in the `filter development`_ section.171172Adding Tests173============174175Adding additional tests works analogous to filters:176177.. sourcecode:: python178179 from mylib import my_cool_test180 env.tests['mycooltest'] = my_cool_test181182Writing tests is explained in the `test development`_ section.183184185.. _installation: installation.txt186.. _context documentation: contextenv.txt187.. _loader: loaders.txt188.. _translators: translators.txt189.. _filter development: filters.txt190.. _test development: tests.txt
deleted:docs/src/devrecipies.txt-139 removed
1=======================2Recipies For Developers3=======================45Here some recipies for application developers.678Automagic Template Variables9============================1011Python allows some magic stack manipulation which can be used to12pass variables to templates automatically. It's not a recommended13way to pass variables to templates but it can be useful for some14small generation scripts etc.1516Just subclass the environment and add an `autorender` function like17this:1819.. sourcecode:: python2021 import sys22 from jinja import Environment2324 class AutoEnvironment(Environment):2526 def autorender(self, template):27 tmpl = self.get_template(template)28 return tmpl.render(sys._getframe(1).f_locals)2930You can use it now like this:3132.. sourcecode:: python3334 def foo():35 seq = range(10)36 foo = "blub"37 return env.autorender('foo.html')3839In the template you can now access the local variables `seq` and `foo`.404142Using Django Filters with Jinja43===============================4445If you use Jinja in django and want to use some of the filters that46are part of the django core you can use this snippet:4748.. sourcecode:: python4950 def convert_django_filter(f):51 def filter_factory(*args):52 def wrapped(env, ctx, value):53 return f(value, *args)54 return wrapped55 return filter_factory5657You can now convert django filters for jinja using `convert_filter`. *Note*:58Django only supports one filter argument. Because of this limitation you59shouldn't pass it more arguments than it accepts. Because django uses some60introspection to find out if a filter accepts an argument weird things can61happen if you call it with an incompatible argument count.6263You can now register django filters for a jinja environment:6465.. sourcecode:: python6667 from django.template.defaultfilters import date68 env.filters['date'] = convert_django_filter(date)6970And use it:7172.. sourcecode:: jinja7374 {{ entry.pub_date|date }}7576Also keep in mind that Jinja knows about keywords, thus you cannot have a filter77that is called `pluralize` for example.7879Such a conversion function is also part of the djangosupport module which was80introduced in Jinja 1.2. It's explained on the `Framework Integration`_ page.818283Using Jinja in Django84=====================8586.. admonition:: Note8788 This section is more or less obsolete as of Jinja 1.2 which provides a89 djangosupport module, covered on the `Framework Integration`_ page.9091This snippet was contributed by Bryan McLemore. It provides a `render_to_response`92function similar to the one shipped with django just that it uses Jinja for93rendering. It applies the context processors on the context and consumes a94`RequestContext`:9596.. sourcecode:: python9798 from django.template.context import get_standard_processors99 from django.http import HttpResponse100 from jinja import Environment, FileSystemLoader, ChoiceLoader101 from django.conf import settings102103 loaders = []104 for location in settings.TEMPLATE_DIRS:105 loaders.append(FileSystemLoader(location))106 env = Environment(loader=ChoiceLoader(loaders))107108 def render_to_response(template, context, request=None):109 template = env.get_template(template)110 if request:111 for processor in get_standard_processors():112 context.update(processor(request))113 return HttpResponse(template.render(context))114115116If you want to plug Jinja into the Django i18n system you can use this117environment class:118119.. sourcecode:: python120121 from jinja import Environment122 from django.utils.translation import gettext, ngettext123124 class DjangoTranslator(object):125126 def __init__(self):127 self.gettext = gettext128 self.ngettext = ngettext129130 class DjangoEnvironment(Environment):131132 def get_translator(self, context):133 return DjangoTranslator()134135Because Django uses gettext internally we can create just assign the136ngettext and gettext functions directly to the translator class.137138139.. _Framework Integration: frameworks.txt
deleted:docs/src/escaping.txt-71 removed
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), a comment or variable element you can remove44the whitespaces after 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 %}
deleted:docs/src/filters.txt-73 removed
1================2Filter Functions3================45Filters are a powerful feature of Jinja taken from django which probably took6it from UNIX. The idea is that you "pipe" a value through some filters to7do something with it. For example convert it to upper case, escape it or8replace a substring.910Jinja comes with some builtin filters explained in the `designer documentation`_.1112Writing Filters13===============1415A filter basically is a factory function, a function that returns another16function. We do this because filters can get an unlimited amount of positional17arguments and aditionally should gain access to the environment, context and18piped value. A simple filter looks like this:1920.. sourcecode:: python2122 def do_join(d=u''):23 def wrapped(env, context, value):24 tmp = []25 for item in value:26 tmp.append(env.to_unicode(item))27 return d.join(tmp)28 return wrapped2930Now you have to register that filter on an environment:3132.. sourcecode:: python3334 env.filters['join'] = do_join3536In fact this filter is already bundled so you won't see any effect. But it37should explain how such a filter looks like. The template designer can just38trigger the outer code (i.e. call `join` with or without arguments). The39returned function is then processed by the jinja template engine once all40filters are created.4142If you want to create filters that just operate on a string (in fact unicode43objects) you can use the `stringfilter` decorator:4445.. sourcecode:: python4647 from jinja.filters import stringfilter4849 @stringfilter50 def do_strip(value):51 return value.strip()5253The wrapped function is created internally by the decorator, any positional54arguments are forwarded to the filter function. The first argument is always55the value already converted into a string.5657If you're using Jinja with django and want to use the django filters in Jinja58have a look at the `developer recipies`_ page.5960*new in Jinja 1.1* additionally to the `stringfilter` decorator there is now61a similar decorator that works exactly the same but does not convert values62to unicode:6364.. sourcecode:: python6566 from jinja.filters import simplefilter6768 @simplefilter69 def do_add(value, to_add):70 return value + to_add7172.. _designer documentation: builtins.txt73.. _developer recipies: devrecipies.txt
deleted:docs/src/frameworks.txt-247 removed
1=====================2Framework Integration3=====================45Starting with Jinja 1.1 it's possible to embed Jinja into some of the existing6frameworks a lot easier. When speaking of frameworks we only refer to `Pylons`_7which has a working implementation of the TurboGears template specification.89Since the whole situation is problematic because of various reasons (kid10specific, uses dotted names for template loading, package name prefix etc.)11we worked around some of the problems by using pylons specific workarounds.1213Jinja also ships an implementation for a hypothetical template abstraction layer14called `General Template Interface`_ which isn't implemented by any existing15framework so far. This specification however tries to solve the problems that16exist in Buffet.171819Buffet20======2122The buffet specification proposes that templates are named in dotted names. That23means `foo.bar` and not `foo/bar.html`. The dotted notation has the disadvantage24that you cannot specify the filename extension. In recent pylons versions it's25however possible to load templates with their native path too if you prefix the26template name with a foreslash (`/foo/bar.html`). If you don't specify the27extension it will assume `.html` for the dotted notation.2829Here the list of configuration values:3031======================= ======================================================32``jinja.extension`` The template extension when templates are loaded using33 the dotted notation. Defaults to ``html``.34``jinja.environment`` If this is provided it must be the only configuration35 value and it's used as jinja environment. In that36 case all other configuration parameters except of37 ``jinja.extension`` are ignored.38``jinja.searchpath`` If provided a new file system loader with this39 search path is instanciated.40``jinja.package`` Name of the python package containing the41 templates. If this and ``package_path`` is42 defined a `PackageLoader` is used.43``jinja.package_path`` Path to the templates inside of a package.44``jinja.loader_func`` Function that takes the name of the template to45 load. If it returns a string or unicode object46 it's used to load a template. If the return47 value is None it's considered missing.48``jinja.getmtime_func`` Function used to check if templates requires49 reloading. Has to return the UNIX timestamp of50 the last template change or 0 if this template51 does not exist or requires updates at any cost.52``jinja.use_memcache`` Set this to ``True`` to enable memory caching.53 This is usually a good idea in production mode,54 but disable it during development since it won't55 reload template changes automatically.56 This only works in persistent environments like57 FastCGI.58``jinja.memcache_size`` Number of template instance you want to cache.59 Defaults to ``40``.60``jinja.cache_folder`` Set this to an existing directory to enable61 caching of templates on the file system. Note62 that this only affects templates transformed63 into python code. Default is ``None`` which means64 that caching is disabled.65``jinja.auto_reload`` Set this to `False` for a slightly better66 performance. In that case of `getmtime_func`67 not being provided this won't have an effect.68======================= ======================================================6970All other options that start with `jinja.` are automatically forwarded to the71environment constructor.7273In pylons for example you can use jinja as buffet plugin like this:7475Edit the `yourproject/config/middleware.py` and add this to `config.init_app`:7677.. sourcecode:: python7879 config.add_template_engine('jinja', '', {80 'jinja.package': 'yourapplication',81 'jinja.package_path': 'res/templates',82 'jinja.use_memcache': True83 })8485Note that it's a good idea to set the second parameter to an empty string.86It's meant to be used as replacement for the turbogears package name but87Jinja assumes that the name of the template does not include the package88path.8990.. admonition:: Note9192 Special note for pylons users. Jinja will be unable to request attributes93 from the special `c` object, unless you set `strict_c` to `True` in the94 `environment.py`:9596 .. sourcecode:: python9798 return pylons.config.Config(tmpl_options, map, paths, strict_c=True)99100You can then render the template in the view like this:101102.. sourcecode:: python103104 class ExampleController(BaseController):105106 def index(self):107 c.title = "Your Page"108 c.message = 'hi'109 return render_response('jinja', 'test_template')110111 def download(self):112 c.title = "Downloads"113 c.downloads = [1, 2, 3]114 return render_response('jinja', '/downloads.html')115116With the settings from above rendering the `index` action will result in117rendering the template ``res/templates/test_template.html`` where res is118a folder in the ``yourapplication`` python package.119120The `downloads` action uses the pylons specific leading foreslash notation.121122123General Template Interface124==========================125126Because nobody implemented this specification so far it's not documented here127but in the sourcecode of the `plugin module`_. The specification itself is128explained on the pocoo trac on the `General Template Interface`_ wiki page.129130131Django132======133134Using Jinja in django is straightforward because django has a pretty low135level response interface. Just have a look at the `developer recipies`_,136there are some examples for django. Starting with Jinja 1.2 there is also137a contrib module that simplifies using Jinja in an unicode enabled django.138139Quickstart140----------141142To get started execute the following code at the bottom of your settings.py143or in some general application file such as urls.py or a central module. The144only thing that matters is that it's executed right *after* the settings145were set up and *before* `django.contrib.jinja` is imported::146147 from jinja.contrib import djangosupport148 djangosupport.configure()149150What this does is setting up a Jinja environment for this django instance151with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default152django filters such as `date` and `timesince` which are not available in153Jinja per default. If you want to change the list you can provide others154by passing a list with filter import names as `convert_filters` keyword155argument.156157All other keyword arguments are forwarded to the environment. If you want158to provide a loader yourself pass it a loader keyword argument.159160Rendering Templates161-------------------162163To render a template you can use the functions `render_to_string` or164`render_to_response` from the `django.contrib.jinja` module::165166 from django.contrib.jinja import render_to_response167 resp = render_to_response('Hello {{ username }}!', {168 'username': req.session['username']169 }, req)170171`render_to_string` and `render_to_response` take at least the name of172the template as argument, then the optional dict which will become the173context. If you also provide a request object as third argument the174context processors will be applied.175176`render_to_response` also takes a forth parameter which can be the177content type which defaults to `DEFAULT_CONTENT_TYPE`.178179Converting Filters180------------------181182One of the useful objects provided by `django.contrib.jinja` is the183`register` object which can be used to register filters, tests and184global objects. You can also convert any filter django provides in185a Jinja filter using `convert_django_filter`::186187 from django.contrib.jinja import register, convert_django_filter188 from django.template.defaultfilters import floatformat189190 register.filter(convert_django_filter(floatformat), 'floatformat')191192Available methods on the `register` object:193194``object (obj[, name])``195 Register a new global as name or with the object's name.196 Returns the function object unchanged so that you can use197 it as decorator if no name is provided.198199``filter (func[, name])``200 Register a function as filter with the name provided or201 the object's name as filtername.202 Returns the function object unchanged so that you can use203 it as decorator if no name is provided.204205``test (func[, name])``206 Register a function as test with the name provided or the207 object's name as testname.208 Returns the function object unchanged so that you can use209 it as decorator if no name is provided.210211``context_inclusion (func, template[, name])``212 Register a function with a name provided or the func object's213 name in the global namespace that acts as subrender function.214215 func is called with the callers context as dict and the216 arguments and keywords argument of the inclusion function.217 The function should then process the context and return a218 new context or the same context object. Afterwards the219 template is rendered with this context.220221 Example::222223 def add_author(context, author=None):224 if author is not None:225 author = Author.objects.get(name=author)226 context['author'] = author227 return context228229 register.context_inclusion(add_author, 'author_details.html',230 'render_author_details')231232 You can use it in the template like this then::233234 {{ render_author_details('John Doe') }}235236``clean_inclusion (func, template[, name[, run_processors]])``237 Works like `context_inclusion` but doesn't use the calles238 context but an empty context. If `run_processors` is `True`239 it will lookup the context for a `request` object and pass240 it to the render function to apply context processors.241242243244.. _Pylons: http://www.pylonshq.com/245.. _General Template Interface: http://trac.pocoo.org/wiki/GeneralTemplateInterface246.. _plugin module: http://trac.pocoo.org/browser/jinja/trunk/jinja/plugin.py247.. _developer recipies: devrecipies.txt
deleted:docs/src/fromdjango.txt-108 removed
1===============================2Differences To Django Templates3===============================45If you have previously worked with Django templates, you should find Jinja very6familiar. In fact, most of the syntax elements look and work the same.78However, Jinja provides some more syntax elements covered in the documentation9and some work a bit different.1011Method Calls12============1314In Django method calls work implicitly. With Jinja you have to specify that you15want to call an object. Thus this Django code:1617.. sourcecode:: django1819 {% for page in user.get_created_pages %}20 ...21 {% endfor %}2223will look like this in Jinja:2425.. sourcecode:: jinja2627 {% for page in user.get_created_pages() %}28 ...29 {% endfor %}3031This allows you to pass variables to the function which is also used for32macros and loop recursion, both features that don't exist in Django.3334Conditions35==========3637In Django you can use the following constructs to check for equality:3839.. sourcecode:: django4041 {% ifequals foo "bar" %}42 ...43 {% else %}44 ...45 {% endifequals %}4647In Jinja you can use the normal ``if`` statement in combination with48operators:4950.. sourcecode:: jinja5152 {% if foo == 'bar' %}53 ...54 {% else %}55 ...56 {% endif %}5758You can also have multiple ``elif`` branches in your template:5960.. sourcecode:: jinja6162 {% if something %}63 ...64 {% elif otherthing %}65 ...66 {% elif foothing %}67 ...68 {% else %}69 ...70 {% endif %}7172Filter Arguments73================7475Jinja provides more than one argument for filters. Also the syntax for argument76passing is different. A template that looks like this in Django:7778.. sourcecode:: django7980 {{ items|join:", " }}8182looks like this in jinja:8384.. sourcecode:: jinja8586 {{ items|join(', ') }}8788In fact it's a bit more verbose but it allows different types of arguments - including89variables - and more than one of them.9091Tests92=====9394In addition to filters there also are tests you can perform using the `is` operator.95Here are some examples:9697.. sourcecode:: jinja9899 {% if user.user_id is odd %}100 {{ user.username|e }} is odd101 {% else %}102 hmm. {{ user.username|e }} looks pretty normal103 {% endif %}104105For a list of supported tests head over to the `syntax reference`_.106107108.. _syntax reference: designerdoc.txt
deleted:docs/src/i18n.txt-113 removed
1====================2Internationalization3====================45Jinja includes support for internationalized templates. Because usually the6application includes i18n/l10n code too there is no script to collect7translatable strings and no default translation interface. A simple8implementation wouldn't fit into every application so there are a few things9you have to do.101112Writing A Translator13====================1415The most important thing is writing a translator and subclassing the16Environment so that Jinja knows about the translator. Then you have to17think of how to resolve the current language. You probably use Jinja in a18multithreaded environment where each thread (request) might want to have19a different language. The best way is putting the current language into20the context, this can work automatically if you create a helper function21for template rendering. But that's up to you.2223However. For many web applications this might be a way:2425.. sourcecode:: python2627 from jinja import Environment28 from myapplication import get_translator2930 class ApplicationTranslator(object):3132 def __init__(self, language):33 self.language = language34 self.translator = get_translator(language)3536 def gettext(self, string):37 return self.translator.ugettext(string)3839 def ngettext(self, singular, plural, n):40 return self.translator.ungettext(singuarl, plural, n)414243 class ApplicationEnvironment(Environment):4445 def get_translator(self, context):46 return ApplicationTranslator(context['LANGUAGE'])474849 env = ApplicationEnvironment()50 tmpl = env.get_template('index.html')51 tmpl.render(LANGUAGE='de_DE')5253This example assumes that you use gettext and have a gettext `Translations`54object which is returned by the `get_translator` function. But you don't55have to use gettext. The only thing Jinja requires is an object with to56functions/methods on it that return and accept unicode strings:57``gettext(string)`` that takes a string, translates and returns it, a58``ngettext(singular, plural, count)`` function that returns the correct plural59form for `count` items. Because some languages have no or multiple plural60forms this is necessary.616263Translator Factory64==================6566With Jinja 1.2 onwards it's possible to use a translator factory67instead of an enviornment subclass to create a translator for a context.68A translator factory is passed a context and has to return a translator.69Because of the way classes work you can also assign a translator class70that takes a context object as only argument as factory.7172Example:7374.. sourcecode:: python7576 from jinja import Environment77 from myapplication import get_translator7879 def translator_factory(context):80 return get_translator(context['LANGUAGE'])8182 env = ApplicationEnvironment(translator_factory=translator_factory)83 tmpl = env.get_template('index.html')84 tmpl.render(LANGUAGE='de_DE')8586This example assumes that the translator returned by `get_translator`87already has a gettext and ngettext function that returns unicode strings.888990Collecting Translations91=======================9293The next step is to collect the translations. Every Jinja environment94provides a function called `get_translations` which collects all95translatable strings from an template.9697Example:9899.. sourcecode:: pycon100101 >>> env.get_translations('index.html')102 [(1, u'foo', None), (2, u'Foo', None), (3, u'%(count)s Foo', u'%(count)s Foos')]103104The first item in the tuple is the linenumer, the second one is the105singular form and the third is the plural form if given.106107Because Jinja is not bound to gettext you can now use these strings to108create translation files for any translation system.109110*New in Jinja 1.1* You can now extract translations from strings according111to the current envrionment settings too by using the environment method112`get_translations_for_string` which takes a string containing a template113as only argument. The return value is the same as for `get_translations`.
deleted:docs/src/index.txt-74 removed
1======================2Documentation Overview3======================45Welcome in the Jinja documentation.67- `Installing Jinja <installation.txt>`_89- **Application Developer Documentation**:1011 - `Quickstart <devintro.txt>`_ - getting started with Jinja1213 - `Template Loaders <loaders.txt>`_ - documentation for the different14 loader types and how to write custom ones.1516 - `Filter Functions <filters.txt>`_ - information about how to write17 custom filter functions.1819 - `Test Functions <tests.txt>`_ - information about how to write20 custom test functions.2122 - `Global Objects <objects.txt>`_ - information about the special global23 namespace in Jinja templates.2425 - `Streaming Interface <streaming.txt>`_ - using Jinja for big templates26 by streaming the output.2728 - `Internationalization <i18n.txt>`_ - how to internationalize applications29 using Jinja templates.3031 - `Alternative Syntax <altsyntax.txt>`_ - changing the default Jinja32 block / variable / comment delimiters.3334 - `API Documentation <api.txt>`_ - API documentation for public Jinja35 objects like `Environment`.3637 - `Translators <translators.txt>`_ - explanation about the Jinja template38 translation interface.3940 - `Framework Integration <frameworks.txt>`_ - integrating Jinja into41 python frameworks.4243 - `Debugging Support <debugging.txt>`_ - debugging Jinja templates.4445 - `Developer Recipies <devrecipies.txt>`_ - tips and tricks for application46 developers.4748- **Template Designer Documentation**:4950 - `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.7172- `Changelog <changelog.txt>`_7374There is also support via IRC on the ``#pocoo`` channel on `irc.freenode.net`.
deleted:docs/src/inheritance.txt-186 removed
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.111213Base Template14=============1516This template, which we'll call ``base.html``, defines a simple HTML skeleton17document that you might use for a simple two-column page. It's the job of18"child" templates to fill the empty blocks with content:1920.. sourcecode:: html+jinja2122 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"23 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">24 <html xmlns="http://www.w3.org/1999/xhtml">25 <head>26 <link rel="stylesheet" href="style.css" />27 <title>{% block title %}{% endblock %} - My Webpage</title>28 {% block html_head %}{% endblock %}29 </head>30 <body>31 <div id="content">32 {% block content %}{% endblock %}33 </div>3435 <div id="footer">36 {% block footer %}37 &copy; Copyright 2006 by <a href="http://mydomain.tld">myself</a>.38 {% endblock %}39 </div>40 </body>4142In this example, the ``{% block %}`` tags define four blocks that child templates43can fill in. All the `block` tag does is to tell the template engine that a44child template may override those portions of the template.454647Child Template48==============4950A child template might look like this:5152.. sourcecode:: html+jinja5354 {% extends "base.html" %}55 {% block title %}Index{% endblock %}5657 {% block html_head %}58 <style type="text/css">59 .important {60 color: #336699;61 }62 </style>63 {% endblock %}64 65 {% block content %}66 <h1>Index</h1>67 <p class="important">68 Welcome on my awsome homepage.69 </p>70 {% endblock %}7172The ``{% extends %}`` tag is the key here. It tells the template engine that73this template "extends" another template. When the template system evaluates74this template, first it locates the parent. It must be always the first tag75in a template but whitespace or a comment is allowed before. This was not76enforced with Jinja 1.0 and 1.1, it does however raise a syntax error with771.2 or later.7879The filename of the template depends on the template loader. For example the80``FileSystemLoader`` allows you to access other templates by giving the81filename. You can access templates in subdirectories with an slash:8283.. sourcecode:: jinja8485 {% extends "layout/default.html" %}8687But this behavior can depend on the application using Jinja.8889Note that since the child template didn't define the ``footer`` block, the90value from the parent template is used instead.9192.. admonition:: Note9394 You can't define multiple ``{% block %}`` tags with the same name in the95 same template. This limitation exists because a block tag works in "both"96 directions. That is, a block tag doesn't just provide a hole to fill - it97 also defines the content that fills the hole in the *parent*. If there were98 two similarly-named ``{% block %}`` tags in a template, that template's99 parent wouldn't know which one of the blocks' content to use.100101102How Inheritance Works Internally103================================104105Inheritance in Jinja is straightforward. If a template contains an106``{% extends %}`` tag it's considered being a child template, otherwise it's107a layout template. In a layout template you can place blocks basically108everywhere. In a child template blocks can only be located either at the109top level or inside another block.110111Data outside of a block in a child template is executed before the layout112template is rendered, thus you can use it to propagate data to the whole113inheritance chain. Having a block in an invalid position you will receive114an syntax error. Here some examples:115116**impossible**:117118 .. sourcecode:: jinja119120 {% extends 'master.html' %}121 {% if some_condition %}122 {% block body %}123 ...124 {% endblock %}125 {% endif %}126127 This can't work because template inheritance works at translation /128 compilation time not at template execution.129130**possible**:131132 .. sourcecode:: jinja133134 {% extends 'master.html' %}135 {% block body %}136 {% if some_condition %}137 {% block myblock %}138 ...139 {% endblock %}140 {% endif %}141 {% endblock %}142143 This can work although it probably makes no sense in this specific case.144 However the condition is handled at runtime because it's in a valid block145 and defines a new block subtemplates can override.146147148.. admonition:: Note149150 Unlike Python Jinja does not support multiple inheritance. So you can151 only have one extends tag with only one constant string argument.152153154Super Blocks155============156157Starting with `Jinja 1.1` it's possible to render the contents of the parent158block. By calling it you get the results of the parent block back. If you want159to get the data of the parent you can give it an offset:160161.. sourcecode:: jinja162163 {{ super() }}164 return the parent data165166 {{ super(1) }}167 the same as above168169 {{ super(2) }}170 return the data of the second parent block171172173Block Shortcuts174===============175176With Jinja 1.1 onwards it's possible to have a shortcut syntax for blocks177with few content. The following constructs do the same:178179.. sourcecode:: jinja180181 {% block title %}{{ page_title }}{% endblock %}182183 {% block title page_title %}184185Note that as soon as you specify a second argument it's threated as186short block and Jinja won't look for an closing tag.
deleted:docs/src/installation.txt-89 removed
1============2Installation3============45Jinja requires at least Python 2.3 to work correctly.678Installing a released version9=============================1011As a Python egg (via easy_install)12----------------------------------1314You can install the most recent Jinja version using `easy_install`_::1516 sudo easy_install Jinja1718This will install a Jinja egg in your Python installation's site-packages19directory.2021From the tarball release22-------------------------23241. Download the most recent tarball from the `download page`_252. Unpack the tarball263. ``sudo python setup.py install``2728Note that the last command will automatically download and install29`setuptools`_ if you don't already have it installed. This requires a working30internet connection.3132This will install Jinja into your Python installation's site-packages directory.333435Installing the development version36==================================3738If you want to play around with the code39----------------------------------------40411. Install `mercurial`_422. ``svn co http://dev.pocoo.org/hg/jinja-main jinja``433. ``cd jinja``444. ``ln -s jinja /usr/lib/python2.X/site-packages``4546As an alternative to steps 4 you can also do ``python setup.py develop``47which will install the package via setuptools in development mode. This also48has the advantage that the c extensions are compiled.4950If you just want the latest features and use them51-------------------------------------------------5253::54 55 sudo easy_install Jinja==dev5657This will install a Jinja egg containing the latest Subversion trunk code58in your Python installation's site-packages directory. Every time the command59is run, the sources are updated from Subversion.606162Windows Installation Information63================================6465On windows computers without Visual Studio 2003 Jinja is unable to compile the66C extensions. This is usually not a problem because there is a fallback for67native Python implementations of those C libraries. However under certain68conditions the installation may fail with an error message. In that case try69to disable the extensions by passing the following parameters to setup.py::7071 python setup.py install --without-speedups --without-extended-debugger727374Documentation75=============7677The egg builds include a documentation which is available in the ``docs`` folder78of the egg. If you're running linux you will find the documentation here::7980 file:///usr/lib/python2.X/site-packages/Jinja-Y.Z-py2.X.egg/docs/index.html8182where ``X``, ``Y`` and ``Z`` must be replaced by the python / jinja version83number.848586.. _download page: http://jinja.pocoo.org/download.html87.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools88.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall89.. _mercurial: http://www.selenic.com/mercurial/
deleted:docs/src/loaders.txt-245 removed
1================2Template Loaders3================45This part of the documentation explains how to use and write a template loader.67Builtin Loaders8===============910This list contains the builtin loaders you can use without further11modification:1213[[list_of_loaders]]1415Loader Baseclasses16==================1718With Jinja 1.1 onwards all the loaders have (except of the uncached)19baseclasses. You can use them to mix your own caching layer in. This technique20is described below. The `BaseLoader` itself is also a loader baseclass but21because it's the baseclass of all loaders it's covered in the "Developing22Loaders" section.2324[[list_of_baseloaders]]2526Developing Loaders27==================2829Template loaders are just normal Python classes that have to provide some30functions used to load and translate templates. Because some of the tasks31a loader has to do are redundant there are some classes that make loader32development easier.3334Here the implementation of a simple loader based on the `BaseLoader` from35`jinja.loaders`:3637.. sourcecode:: python3839 import codecs40 from os.path import join41 from jinja.loaders import BaseLoader42 from jinja.exceptions import TemplateNotFound4344 class SimpleLoader(BaseLoader):45 46 def __init__(self, path):47 self.path = path4849 def get_source(self, environment, name, parent):50 filename = join(self.path, name)51 if not path.exists(filename):52 raise TemplateNotFound(name)53 f = codecs.open(filename, 'r', environment.template_charset)54 try:55 return f.read()56 finally:57 f.close()5859The functions `load` and `parse` which are a requirement for a loader are60added automatically by the `BaseLoader`. Instead of the normal `BaseLoader`61you can use one of the other base loaders that already come with a proper62`get_source` method for further modification. Those loaders however are63new in Jinja 1.1.6465CachedLoaderMixin66-----------------6768Additionally to the `BaseLoader` there is a mixin class called69`CachedLoaderMixin` that implements memory and disk caching of templates.70Note that you have to give it a higher priority in the MRO than the71`BaseLoader` which means that's the first base class when inheriting from it:7273.. sourcecode:: python7475 import codecs76 from os.path import join, getmtime, exists77 from jinja.loaders import BaseLoaderCachedLoaderMixin78 from jinja.exceptions import TemplateNotFound7980 class CachedLoader(CachedLoaderMixin, BaseLoader):81 82 def __init__(self, path):83 self.path = path84 CachedLoaderMixin.__init__(self,85 True, # use memory caching86 40, # for up to 40 templates87 '/tmp', # additionally save the compiled templates in /tmp88 True, # and reload cached templates automatically if changed89 'foo' # optional salt used to keep templates with the same90 # name in the same cache folder, but from different91 # loaders. New in Jinja 1.1 and can be omitted.92 )9394 def get_source(self, environment, name, parent):95 filename = join(self.path, name)96 if not path.exists(filename):97 raise TemplateNotFound(name)98 f = codecs.open(filename, 'r', environment.template_charset)99 try:100 return f.read()101 finally:102 f.close()103104 def check_source_changed(self, environment, name):105 fn = join(self.path, name)106 if exists(fn):107 return getmtime(fn)108 return -1109110You don't have to provide the `check_source_changed` method. If it doesn't111exist the option `auto_reload` won't have an effect. Also note that the112`check_source_changed` method must not raise an exception if the template113does not exist but return ``-1``. The return value ``-1`` is considered114"always reload" whereas ``0`` means "do not reload". The default return115value for not existing templates should be ``-1``.116117For the default base classes that come with Jinja 1.1 onwards there exist118also concrete implementations that support caching. The implementation119just mixes in the `CachedLoaderMixin`.120121MemcachedLoaderMixin122--------------------123124*New in Jinja 1.1*125126The `MemcachedLoaderMixin` class adds support for `memcached`_ caching.127There is only one builtin loader that mixes it in: The128`MemcachedFileSystemLoader`. If you need other loaders with this mixin129you can easily subclass one of the existing base loaders. Here an example130for the `FunctionLoader`:131132.. sourcecode:: python133134 from jinja.loaders import FunctionLoader, MemcachedLoaderMixin135136 class MemcachedFunctionLoader(MemcachedLoaderMixin, FunctionLoader):137138 def __init__(self, loader_func):139 BaseFunctionLoader.__init__(self, loader_func)140 MemcachedLoaderMixin.__init__(self,141 True, # use memcached142 60 * 60 * 24 * 7, # 7 days expiration143 ['127.0.0.1:11211'], # the memcached hosts144 'template/' # string prefix for the cache keys145 )146147This mixin requires the `python-memcached`_ library.148149.. _memcached: http://www.danga.com/memcached/150.. _python-memcached: http://www.tummy.com/Community/software/python-memcached/151152153How Mixin Classes Work154======================155156The idea of the cached loader mixins is that you override the `load`157method of the other base class so that it's only called to get the data158from the loader and put it into a cache and then bypass the original `load`.159160This works because mixin classes, as well as the loaders are so called "new161style classes" with a MRO (method resolution order). So it's possible to162access the parent without actually knowing the name of it.163164Here as small mixin class that stores everything after loading in a165dict:166167.. sourcecode:: python168169 class SimpleCacheMixin(object):170171 def __init__(self):172 self.__cache = {}173174 def load(self, environment, name, translator):175 if name in self.__cache:176 return self.__cache[name]177 tmpl = super(SimpleCacheMixin, self).load(environment, name,178 translator)179 self.__cache[name] = tmpl180 return tmpl181182You can then mix the class in like any other mixin class. Note that183all non public attributes **must** be prefixed with two underscores to184enable the name mangling. Otherwise the mixin class could break the185internal structure of the loader.186187The ``super(SimpleCacheMixin, self)`` call returns an object that looks188up all the attributes you request in all the parent classes. The189`SimpleCacheMixin` just has the `object` parent which makes it a new190style class, but as soon as a loader is mixed in it will call the191`load` method of the loader that is the other parent of the resulting192class. Here a full example.193194Combining Everything195====================196197Here a full example with a custom cache mixin and a custom base loader:198199.. sourcecode:: python200201 import codecs202 from os.path import join203 from jinja.loaders import BaseLoader204 from jinja.exceptions import TemplateNotFound205206 class SimpleBaseLoader(BaseLoader):207 208 def __init__(self, path):209 self.path = path210211 def get_source(self, environment, name, parent):212 filename = join(self.path, name)213 if not path.exists(filename):214 raise TemplateNotFound(name)215 f = codecs.open(filename, 'r', environment.template_charset)216 try:217 return f.read()218 finally:219 f.close()220221222 class SimpleCacheMixin(object):223224 def __init__(self):225 self.__cache = {}226227 def load(self, environment, name, translator):228 if name in self.__cache:229 return self.__cache[name]230 tmpl = super(SimpleCacheMixin, self).load(environment, name,231 translator)232 self.__cache[name] = tmpl233 return tmpl234235236 class SimpleLoader(SimpleBaseLoader, SimpleCacheMixin):237238 def __init__(self, path):239 SimpleBaseLoader.__init__(self, path)240 SimpleCacheMixin.__init__()241242You can of course put all the functionallity into the `SimpleLoader` but then243you cannot exchange parts of it without rewriting much code. In the example244above replacing the `SimpleCacheMixin` with a `MemcachedLoaderMixin` is a245matter of 20 seconds.
deleted:docs/src/objects.txt-154 removed
1==============2Global objects3==============45This section covers the behavior of global objects in the Jinja namespace and6also the behavior of their attributes.789Functions10=========1112`Filters`_ and `Tests`_ are special kind of functions you cannot call without13and argument. Global functions are different. Those are really just ordinary14python functions. You can register them on the global namespace easily:1516.. sourcecode:: python1718 def my_function():19 return [1, 2, 3]2021 env.globals['my_function'] = my_function2223In the template you can not call it like this:2425.. sourcecode:: jinja2627 {{ my_function() }}2829Of couse you can pass any argument to it. But what if you want to access the30context or environment? In that case you have to decorate a function or mark31it (both work exactly the same, but the decorator way is probably nicer if you32have python >= 2.4):3334.. sourcecode:: python3536 from cgi import escape37 from pprint import pformat38 from jinja.datastructure import contextcallable3940 @contextcallable41 def printcontext(env, context):42 result = []43 for key, value in context.to_dict():44 result.append('<tr><th>%s</th><td>%r</td></tr>' %45 (escape(unicode(key)), escape(pformat(value))))46 return '<table>%s</table>' % u'\n'.join(result)4748If this function is registered in the environment namespace then and called49from the template it should return the content of the context as simple html50template. Of course you can modify the context too. For more informations about51the context object have a look at the `context object`_ documentation.5253The new ``{% call %}`` tag that exists with Jinja 1.1 onwards can not only54be used with Jinja macros but also with Python functions. If a template55designers uses the ``{% call %}`` tag to call a function provided by the56application Jinja will call this function with a keyword argument called57`caller` which points to a `function`. If you call this function (optionally58with keyword arguments that appear in the context) you get a string back59that was the content of that block. This should explain this:6061.. sourcecode:: python6263 def make_dialog(title, caller=None):64 body = ''65 if caller:66 body = caller(title=title)67 return '<div class="dialog"><h2>%s</h2>%s</div>' % (title, body)6869This can be used like this in the template now:7071.. sourcecode:: html+jinja7273 {% call make_dialog('Dialog Title') %}74 This is the body of the dialog entitled "{{ title }}".75 {% endcall %}7677Deferred Values78===============7980You can pass functions to the template that are called to provide values at81first access. Say you want to pass the list of recently written comments to82all templates. But not necessarily every template will render that. In that83situation you can create a function that returns that value and wrap it in an84`Deferred` object. The first time a template accesses the variable then the85`Deferred` object is resolved:8687.. sourcecode:: python8889 from jinja.datastructure import Deferred90 from yourapplication.models import Comments9192 def get_recent_comments(env, context, name):93 # do what ever you want here.94 return Comments.get_recent(10)9596 env.globals['recent_comments'] = Deferred(get_recent_comments)9798The function is always called with the same arguments. The first one is the99current environment, the second the context and the third is the name of the100variable. In this example ``recent_comments``.101102The value is cached until rendering/streaming finished.103104Unsafe Methods / Attributes105===========================106107Because Jinja is sandboxed it provides several ways to prevent unsafe attribute108access. You can mark both attributes and methods as unsafe:109110.. sourcecode:: python111112 from jinja.datastructure import unsafe113114 class MyModel(...):115116 # just give access to a and b. Default is all117 # note that this also disallows the functions from below.118 # if you use jinja_allowed_attributes you don't have add the119 # code below since methods are treated as attributes too.120 jinja_allowed_attributes = ['a', 'b']121122 def __init__(self, ...):123 ...124 self.a = ...125 self.b = ...126127 # python2.4 way of marking methods128 @unsafe129 def save(self):130 """Save the model."""131132 # python2.3 way for the same133 def delete(self):134 """Delete the model."""135 delete.jinja_unsafe_call = True136137138Bypassing Automatic Filtering139=============================140141With Jinja 1.1 it's possible to assign filters to any variable printed. Of142course there are ways to bypass that in order to make sure an object does143not get escaped etc.144145In order to disable automatic filtering for an object you have to make146sure that it's either an subclass of `unicode` or implements a147`__unicode__` method. `__str__` will work too as long as the return value148only contains ASCII values. Additionally you have to add an attribute to149that object named `jinja_no_finalization` and set that to `True`.150151152.. _Filters: filters.txt153.. _Tests: tests.txt154.. _context object: contextenv.txt
deleted:docs/src/recipies.txt-184 removed
1========2Recipies3========45Here are some typical recipes for the usage of Jinja templates.67Alternating Rows8================910If you want to have different styles for each row of a table or11list you can use the ``cycle`` tag:1213.. sourcecode:: html+jinja1415 <ul>16 {% for row in sequence %}17 <li class="{% cycle 'even', 'odd' %}">{{ row|e }}</li>18 {% endfor %}19 </ul>2021``cycle`` can take an unlimited amount of strings. Each time this22tag is encountered the next item from the list is rendered.23If you pass it just one argument it's meant to be a sequence.242526Active Menu Item27================2829Often you want to have a navigation bar with an active navigation30item. This is really simple to achieve. Because ``set`` tags outside31of ``blocks`` are global you can do something like this:3233**layout.html**:3435 .. sourcecode:: html+jinja3637 {% set navigation_bar = [38 ('/', 'index', 'Index'),39 ('/downloads/', 'downloads', 'Downloads'),40 ('/about/', 'about', 'About')41 ] %}42 ...43 <ul id="navigation">44 {% for href, id, caption in navigation_bar %}45 <li{% if id == active_page %} class="active"{% endif46 %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>47 {% endfor %}48 </ul>49 ...5051**index.html**:5253 .. sourcecode:: jinja5455 {% extends "layout.html" %}56 {% set active_page = "index" %}575859Sitemap60=======6162To create a sitemap you can either use the ``for`` tag or a ``macro``63that calls itself. The datastructures should look like this:6465.. sourcecode:: python6667 {'sitemap': [68 dict(69 caption='Pages',70 children=[71 dict(href='index.html', caption='Index'),72 dict(href='downloads.html', caption='Downloads'),73 dict(74 caption='Users',75 children=[76 dict(href='peter.html',77 caption='Peter'),78 dict(href='max.html',79 caption='Max'),80 dict(href='suzan.html',81 caption='Suzan')82 ]83 ),84 dict(85 caption='Files',86 children=[87 dict(88 caption='Images',89 children=[90 dict(href='vienna.html',91 caption='Vienna'),92 dict(href='roma.html',93 caption='Roma'),94 dict(href='tokyo.html',95 caption='Tokyo')96 ]97 ),98 dict(99 caption='Videos',100 children=[101 dict(href='party.html',102 caption='Party')103 ]104 )105 ]106 )107 ]108 ),109 dict(caption='Foo', href='foo.html')110 dict(caption='About', href='about.html')111 ]}112113Now you can create a sitemap using ``for``:114115.. sourcecode:: html+jinja116117 <ul class="sitemap">118 {% for item in sitemap recursive %}119 <li><a href="{{ item.href|e }}">{{ item.caption|e }}</a>120 {% if item.children %}<ul>{{ loop(item.children) }}</ul>{% endif %}</li>121 {% endfor %}122 </ul>123124Or by using a ``macro`` that calls itself:125126.. sourcecode:: html+jinja127128 {% macro render_sitemap items %}129 {% for item in items %}130 <li><a href="{{ item.href|e }}">{{ item.caption|e }}</a>131 {% if item.children %}<ul>{{ render_sitemap(item.children) }}</ul>{% endif %}</li>132 {% endfor %}133 {% endmacro %}134 <ul class="sitemap">{{ render_sitemap(sitemap) }}</ul>135136137Using A Block Multiple Times138============================139140Blocks have the small disadvantage that they work both ways which is a problem141if you want to render a block two times on a page. Here a nice little142workaround for this limitation:143144.. sourcecode:: html+jinja145146 <html>147 <head>148 <title>{% filter capture('title') %}{%149 block title %}{% endblock %}{%150 endfilter %}</title>151 </head>152 <body>153 <div class="head">{{ title }}</div>154 </body>155 </html>156157Or if you use the `capture` filter in `clean` mode:158159.. sourcecode:: html+jinja160161 {% filter capture('title', True)|trim %}162 {% block title %}{% endblock %}163 {% endfilter %}164 <html>165 <head>166 <title>{{ title }}</title>167 </head>168 <body>169 <div class="head">{{ title }}</div>170 </body>171 </html>172173174Vim Syntax Highlighting175=======================176177Because of the similar syntax to django you can use the django highlighting178plugin for jinja too. There is however a Jinja syntax highlighting plugin179too which supports all of the syntax elements.180181You can download it from the vim webpage: `jinja.vim`_182183184.. _jinja.vim: http://www.vim.org/scripts/script.php?script_id=1856
deleted:docs/src/scopes.txt-186 removed
1============================2Scopes and Variable Behavior3============================45This section of the documentation covers the Jinja behavior regarding6variable visibility.789Scopes10======1112Jinja has multiple scopes. A scope is something like a new transparent foil on13a stack of foils. You can only write to the outermost foil but read all of them14since you can look through them. If you remove the top foil all data on that15foil disappears. Some tags in Jinja add a new layer to the stack. Currently16these are `block`, `for`, `macro` and `filter`. This means that variables and17other elements defined inside a macro, loop or some of the other tags listed18above will be only available in that block. Here an example:1920.. sourcecode:: jinja2122 {% macro angryhello name %}23 {% set angryname = name|upper %}24 Hello {{ name }}. Hello {{ name }}!25 HELLO {{ angryname }}!!!!!!11126 {% endmacro %}2728The variable ``angryname`` just exists inside the macro, not outside it.2930Defined macros appear on the context as variables. Because of this, they are31affected by the scoping too. A macro defined inside of a macro is just available32in those two macros (the macro itself and the macro it's defined in).333435Template Globals36================3738A special threatment exists for template code outside of visible blocks in39child templates. This code will be executed **before** the layout template40code. Thus it can be used to propagate values back to the layout template or41import macros from templates for rendering.4243Such code can output data but it won't appear in the final rendering. So no44additional whitespace will pollute the template.4546Because this code is executed before the actual layout template code it's47possible that the layout code overrides some of those variables. Usually48this is not a problem because of different variable names but it can be49a problem if you plan to specify default values.5051In that case you have to test if the variable is not defined before setting52it:5354.. sourcecode:: jinja5556 {% if not page_title %}57 {% set page_title = 'Default Page Title' %}58 {% endif %}5960You can of course also use the `|default` filter.6162.. admonition:: Explanation6364 This template stored as `a.html`:6566 .. sourcecode:: html+jinja6768 <title>{{ title|default('Untitled') }}</title>69 <body>{% block body %}{% endblock %}7071 ...and this child template stored as `b.html`:7273 .. sourcecode:: html+jinja7475 {% extends 'a.html' %}76 {% include 'macros.tmpl' %}77 {% set title = 'My Page' %}78 {% block body %}{{ wrap(42) }}{% endblock %}7980 ...and this code in `macros.tmpl`:8182 .. sourcecode:: html+jinja8384 {% macro wrap(text) %}85 [{{ text }}]86 {% endmacro %}8788 ..will translate to something with the same semantics as this (just89 that the value is not stored in a variable):9091 .. sourcecode:: html+jinja9293 {% filter capture('captured', true) %}94 {% macro wrap(text) %}95 [{{ text }}]96 {% endmacro %}97 {% set title='My Page' %}98 {% endfilter %}99 <title>{{ title|default('Untitled') }}</title>100 <body>101 {{ wrap(42) }}102 </body>103104.. admonition:: Note105106 This implementation was improved in Jinja 1.1. In Jinja 1.0 blocks that107 were not top-level were not propagated to the layout template. This made108 it impossible to use conditional expressions for inclusion in non root109 templates.110111112Undefined Variables113===================114115If you have already worked with python you probably know about the fact that116undefined variables raise an exception. This is different in Jinja. There is a117special value called `undefined` that represents values that do not exist.118119Depending on the configuration it will behave different.120121In order to check if a value is defined you can use the `defined` test:122123.. sourcecode:: jinja124125 {{ myvariable is not defined }}126 will return true if the variable does not exist.127128`SilentUndefined`:129130 The silent `undefined` is the default behavior. The `undefined` object works131 complete different from any variables you maybe know. If you print it132 using ``{{ variable }}`` it will not appear because it's literally empty.133 If you try to iterate over it, it will work. But no items are returned.134135 In order to check if a value is defined you can use the `defined` test:136137 There are also some additional rules regarding this special value. Any138 mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand139 as result:140141 .. sourcecode:: jinja142143 {{ undefined + "foo" }}144 returns "foo"145146 {{ undefined - 42 }}147 returns 42. Note: not -42!148149 In any expression `undefined` evaluates to `false`. It has no length, all150 attribute calls return undefined, calling too:151152 .. sourcecode:: jinja153154 {{ undefined.attribute().attribute_too[42] }}155 still returns `undefined`.156157`ComplainingUndefined`:158159 Starting with Jinja 1.1 it's possible to replace the default undefined160 object with different values. The other common undefined object which161 comes with Jinja is the `ComplainingUndefined` object.162163 It raises exceptions as soon as you either render it or want to iterate164 over it or try to access attributes etc.165166167Overriding Variables Of Outer Scopes168====================================169170*New in Jinja 1.2*171172Normally you cannot override a variable from an outer scope, you can just hide173it. There is however a way to override a variable from an outer scope using the174`set` tag, postfixed with a bang (!):175176.. sourcecode:: jinja177178 {% set last_item = none %}179 {% for item in seq %}180 {% set last_item = item! %}181 {% endfor %}182183After the iteration `last_item` will point to the item of the last iteration.184185If `last_item` was not defined in the outer scope it would be defined in the186outermost scope.
deleted:docs/src/streaming.txt-74 removed
1===================2Streaming Interface3===================45With Jinja 1.1 onwards it's possible to stream the template output. This is6usually a bad idea because it's slower than `render()` but there are some7situations where it's useful.89If you for example generate a file with a couple of megabytes you may want10to pass the stream to the WSGI interface in order to keep the amount of11memory used low and deliver the output to the browser as fast as possible.1213The streaming interface is straightforward. Instead of using `render()` you14can call `stream()` which does pretty much the same but doesn't return a15string but a `TemplateStream`:1617.. sourcecode:: pycon1819 >>> tmpl = env.from_string("<ul>{% for item in seq %}\n <li>{{ loop.index "20 ... "}} - {{ item }}</li>\n{%- endfor %}</ul>")21 >>> stream = tmpl.stream(seq=range(4))22 >>> stream.next()23 '<ul>'24 >>> stream.next()25 u'\n <li>1 - 0</li>'26 >>> stream.next()27 u'\n <li>2 - 1</li>'28 >>> stream.next()29 u'\n <li>3 - 2</li>'30 >>> stream.next()31 u'\n <li>4 - 3</li>'32 >>> stream.next()33 '</ul>'3435As you can see each iteration is threated as template event here. But also36other tags trigger events. Basically every tag yields one event, the37`print` tag too. The only exception is the variable substitution syntax which38is inserted into the template text data.3940Because some protocols like `WSGI` flush after each iteration if passed as41response iterable it's better to buffer some events internally. You can do42this by enable buffering using `enable_buffering` and passing it the buffer43size which must be greater than one:4445.. sourcecode:: pycon4647 >>> stream.enable_buffering(size=3)48 >>> stream.next()49 u'<ul>\n <li>1 - 0</li>\n <li>2 - 1</li>'50 >>> stream.next()51 u'\n <li>3 - 2</li>\n <li>4 - 3</li></ul>'5253This will buffer 3 events before yielding. Disabling buffering works using the54`disable_buffering` method. You can enable and disable buffering on the fly also55if you have already iterated over that stream. To check if you are in buffered56or unbuffered mode you can use the `.buffered` property:5758.. sourcecode:: pycon5960 >>> stream.buffered61 False62 >>> stream.enable_buffering(20)63 >>> stream.buffered64 True65 >>> stream.disable_buffering()66 >>> stream.buffered67 False6869.. admonition:: Note7071 Jinja uses buffering internally for some constructs like macros. A macro72 call is yielded as one event, independently of the internal structure.7374 The same applies to recursive for loops and `{% filter %}` tags.
deleted:docs/src/templatei18n.txt-83 removed
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.19If you want to use the ``_()`` syntax in an expression and have variables in20the string you can add a substituation marker (``%s``) and use the `|format`21filter to fill the slot:2223.. sourcecode:: jinja2425 {{ _('Hello %s!')|format(username) }}2627If you have more than one substitution variable consider using the28``{% trans %}`` tags or the `|dformat` filter, the latter however is new29in Jinja 1.1.3031If you want to have plural forms too, use the `pluralize` block:3233.. sourcecode:: jinja3435 {% trans users=users %}36 One user found.37 {% pluralize %}38 {{ users }} users found.39 {% endtrans %}4041 {% trans first=(users|first).username|escape, user=users|length %}42 one user {{ first }} found.43 {% pluralize users %}44 {{ users }} users found, the first one is called {{ first }}.45 {% endtrans %}4647If you have multiple arguments, the first one is assumed to be the indicator (the48number that is used to determine the correct singular or plural form. If you49don't have the indicator variable on position 1 you have to tell the `pluralize`50tag the correct variable name.5152Inside translatable blocks you cannot use blocks or expressions (however you can53still use the ``raw`` block which will work as expected). The variable54print syntax (``{{ variablename }}``) is the only way to insert the variables55defined in the ``trans`` header. Filters must be applied in the header.5657.. admonition:: note5859 Please make sure that you always use pluralize blocks where required.60 Many languages have more complex plural forms than the English language.61 62 Never try to workaround that issue by using something like this:6364 .. sourcecode:: jinja6566 {% if count != 1 %}67 {{ count }} users found.68 {% else %}69 one user found.70 {% endif %}7172*New in Jinja 1.1*: It's now possible to use the marker name as implicit73default:7475.. sourcecode:: jinja7677 instead of this version:7879 {% trans username=username %}Hello {{ username }}!{% endtrans %}8081 you can now write this:8283 {% trans username %}Hello {{ username }}!{% endtrans %}
deleted:docs/src/tests.txt-30 removed
1==============2Test Functions3==============45In addition to filters, Jinja also supports test functions. Test functions6always return either ``True`` or ``False``. Inside the template they are available7using the `is` operator.89Jinja comes with some builtin tests listed in the `designer documentation`_.1011Writing Test Functions12======================1314Test functions look exactly like filters mentioned in the `filter documentation`_:1516.. sourcecode:: python1718 def is_even():19 def wrapped(env, context, value):20 return value % 2 == 021 return wrapped2223Now you have to register that test on an environment:2425.. sourcecode:: python2627 env.tests['even'] = is_even2829.. _designer documentation: builtins.txt30.. _filter documentation: filters.txt
deleted:docs/src/translators.txt-10 removed
1===========2Translators3===========45Jinja translates the template sourcecode into executable python code behind6the secenes. This is done by the python translator which is currently the7only shipped translator. Because the interface isn't stable it's also not8recommended yet to write other translators. However for one of the next Jinja9versions a JavaScript translator is planned which allows you to translate10Jinja templates into executable JavaScript code.
added:docs/conf.py+141 added
1# -*- coding: utf-8 -*-2#3# Jinja2 documentation build configuration file, created by4# sphinx-quickstart on Sun Apr 27 21:42:41 2008.5#6# This file is execfile()d with the current directory set to its containing dir.7#8# The contents of this file are pickled, so don't put values in the namespace9# that aren't pickleable (module imports are okay, they're removed automatically).10#11# All configuration values have a default value; values that are commented out12# serve to show the default value.1314import sys, os1516# If your extensions are in another directory, add it here. If the directory17# is relative to the documentation root, use os.path.abspath to make it18# absolute, like shown here.19#sys.path.append(os.path.abspath('some/directory'))2021# General configuration22# ---------------------2324# Add any Sphinx extension module names here, as strings. They can be extensions25# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.26#extensions = []2728# Add any paths that contain templates here, relative to this directory.29templates_path = ['_templates']3031# The suffix of source filenames.32source_suffix = '.rst'3334# The master toctree document.35master_doc = 'index'3637# General substitutions.38project = 'Jinja2'39copyright = '2008, Armin Ronacher'4041# The default replacements for |version| and |release|, also used in various42# other places throughout the built documents.43#44# The short X.Y version.45version = '2.0'46# The full version, including alpha/beta/rc tags.47release = '2.0'4849# There are two options for replacing |today|: either, you set today to some50# non-false value, then it is used:51#today = ''52# Else, today_fmt is used as the format for a strftime call.53today_fmt = '%B %d, %Y'5455# List of documents that shouldn't be included in the build.56#unused_docs = []5758# If true, '()' will be appended to :func: etc. cross-reference text.59#add_function_parentheses = True6061# If true, the current module name will be prepended to all description62# unit titles (such as .. function::).63#add_module_names = True6465# If true, sectionauthor and moduleauthor directives will be shown in the66# output. They are ignored by default.67#show_authors = False6869# The name of the Pygments (syntax highlighting) style to use.70pygments_style = 'sphinx'717273# Options for HTML output74# -----------------------7576# The style sheet to use for HTML and HTML Help pages. A file of that name77# must exist either in Sphinx' static/ path, or in one of the custom paths78# given in html_static_path.79html_style = 'default.css'8081# The name for this set of Sphinx documents. If None, it defaults to82# "<project> v<release> documentation".83#html_title = None8485# Add any paths that contain custom static files (such as style sheets) here,86# relative to this directory. They are copied after the builtin static files,87# so a file named "default.css" will overwrite the builtin "default.css".88html_static_path = ['_static']8990# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,91# using the given strftime format.92html_last_updated_fmt = '%b %d, %Y'9394# If true, SmartyPants will be used to convert quotes and dashes to95# typographically correct entities.96#html_use_smartypants = True9798# Custom sidebar templates, maps document names to template names.99#html_sidebars = {}100101# Additional templates that should be rendered to pages, maps page names to102# template names.103#html_additional_pages = {}104105# If false, no module index is generated.106#html_use_modindex = True107108# If true, the reST sources are included in the HTML build as _sources/<name>.109#html_copy_source = True110111# If true, an OpenSearch description file will be output, and all pages will112# contain a <link> tag referring to it.113#html_use_opensearch = False114115# Output file base name for HTML help builder.116htmlhelp_basename = 'Jinja2doc'117118119# Options for LaTeX output120# ------------------------121122# The paper size ('letter' or 'a4').123#latex_paper_size = 'letter'124125# The font size ('10pt', '11pt' or '12pt').126#latex_font_size = '10pt'127128# Grouping the document tree into LaTeX files. List of tuples129# (source start file, target name, title, author, document class [howto/manual]).130latex_documents = [131 ('index', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', 'manual'),132]133134# Additional stuff for the LaTeX preamble.135#latex_preamble = ''136137# Documents to append as an appendix to all manuals.138#latex_appendices = []139140# If false, no module index is generated.141#latex_use_modindex = True
deleted:docs/generate.py-325 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4 Generate Jinja Documentation5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~67 Generates a bunch of html files containing the documentation.89 :copyright: 2006-2007 by Armin Ronacher, Georg Brandl.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))15import re16import inspect17from datetime import datetime18from cgi import escape1920from docutils import nodes21from docutils.parsers.rst import directives22from docutils.core import publish_parts23from docutils.writers import html4css12425from jinja import Environment2627from pygments import highlight28from pygments.lexers import get_lexer_by_name29from pygments.formatters import HtmlFormatter3031def generate_list_of_filters():32 from jinja.filters import FILTERS33 result = []3435 filters = {}36 for name, f in FILTERS.iteritems():37 if not f in filters:38 filters[f] = ([name], inspect.getdoc(f))39 else:40 filters[f][0].append(name)41 for names, _ in filters.itervalues():42 names.sort(key=lambda x: -len(x))4344 for names, doc in sorted(filters.values(), key=lambda x: x[0][0].lower()):45 name = names[0]46 if len(names) > 1:47 aliases = '\n\n :Aliases: %s\n' % ', '.join(names[1:])48 else:49 aliases = ''5051 doclines = []52 for line in doc.splitlines():53 doclines.append(' ' + line)54 doc = '\n'.join(doclines)55 result.append('`%s`\n%s%s' % (name, doc, aliases))5657 return '\n'.join(result)5859def generate_list_of_tests():60 from jinja.tests import TESTS61 result = []6263 tests = {}64 for name, f in TESTS.iteritems():65 if not f in tests:66 tests[f] = ([name], inspect.getdoc(f))67 else:68 tests[f][0].append(name)69 for names, _ in tests.itervalues():70 names.sort(key=lambda x: -len(x))7172 for names, doc in sorted(tests.values(), key=lambda x: x[0][0].lower()):73 name = names[0]74 if len(names) > 1:75 aliases = '\n\n :Aliases: %s\n' % ', '.join(names[1:])76 else:77 aliases = ''7879 doclines = []80 for line in doc.splitlines():81 doclines.append(' ' + line)82 doc = '\n'.join(doclines)83 result.append('`%s`\n%s%s' % (name, doc, aliases))8485 return '\n'.join(result)8687def generate_list_of_loaders():88 from jinja import loaders as loader_module8990 result = []91 loaders = []92 for item in loader_module.__all__:93 loaders.append(getattr(loader_module, item))94 loaders.sort(key=lambda x: x.__name__.lower())9596 for loader in loaders:97 doclines = []98 for line in inspect.getdoc(loader).splitlines():99 doclines.append(' ' + line)100 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))101102 return '\n\n'.join(result)103104def generate_list_of_baseloaders():105 from jinja import loaders as loader_module106107 result = []108 loaders = []109 for item in dir(loader_module):110 obj = getattr(loader_module, item)111 try:112 if issubclass(obj, loader_module.BaseLoader) and \113 obj.__name__ != 'BaseLoader' and \114 obj.__name__ not in loader_module.__all__:115 loaders.append(obj)116 except TypeError:117 pass118 loaders.sort(key=lambda x: x.__name__.lower())119120 for loader in loaders:121 doclines = []122 for line in inspect.getdoc(loader).splitlines():123 doclines.append(' ' + line)124 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))125126 return '\n\n'.join(result)127128def generate_environment_doc():129 from jinja.environment import Environment130 return '%s\n\n%s' % (131 inspect.getdoc(Environment),132 inspect.getdoc(Environment.__init__)133 )134135e = Environment()136137PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')138139LIST_OF_FILTERS = generate_list_of_filters()140LIST_OF_TESTS = generate_list_of_tests()141LIST_OF_LOADERS = generate_list_of_loaders()142LIST_OF_BASELOADERS = generate_list_of_baseloaders()143ENVIRONMENT_DOC = generate_environment_doc()144CHANGELOG = file(os.path.join(os.path.dirname(__file__), os.pardir, 'CHANGES'))\145 .read().decode('utf-8')146147FULL_TEMPLATE = e.from_string('''\148<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"149 "http://www.w3.org/TR/html4/strict.dtd">150<html>151<head>152 <title>{{ title }} &mdash; Jinja Documentation</title>153 <meta http-equiv="content-type" content="text/html; charset=utf-8">154 <link rel="stylesheet" href="style.css" type="text/css">155 <style type="text/css">156 {{ style|e }}157 </style>158</head>159<body>160 <div id="content">161 {% if file_id == 'index' %}162 <div id="jinjalogo"></div>163 <h2 class="subheading plain">{{ title }}</h2>164 {% else %}165 <h1 class="heading"><span>Jinja</span></h1>166 <h2 class="subheading">{{ title }}</h2>167 {% endif %}168 {% if file_id != 'index' or toc %}169 <div id="toc">170 <h2>Navigation</h2>171 <ul>172 <li><a href="index.html">back to index</a></li>173 </ul>174 {% if toc %}175 <h2>Contents</h2>176 <ul class="contents">177 {% for key, value in toc %}178 <li><a href="{{ key }}">{{ value }}</a></li>179 {% endfor %}180 </ul>181 {% endif %}182 </div>183 {% endif %}184 <div id="contentwrapper">185 {{ body }}186 </div>187 </div>188</body>189<!-- generated on: {{ generation_date }}190 file id: {{ file_id }} -->191</html>\192''')193194PREPROC_TEMPLATE = e.from_string('''\195<!-- TITLE -->{{ title }}<!-- ENDTITLE -->196<!-- TOC -->{% for key, value in toc %}<li><a href="{{197 key }}">{{ value }}</a></li>{% endfor %}<!-- ENDTOC -->198<!-- BODY -->{{ body }}<!-- ENDBODY -->\199''')200201def pygments_directive(name, arguments, options, content, lineno,202 content_offset, block_text, state, state_machine):203 try:204 lexer = get_lexer_by_name(arguments[0])205 except ValueError:206 # no lexer found207 lexer = get_lexer_by_name('text')208 parsed = highlight(u'\n'.join(content), lexer, PYGMENTS_FORMATTER)209 return [nodes.raw('', parsed, format="html")]210pygments_directive.arguments = (1, 0, 1)211pygments_directive.content = 1212directives.register_directive('sourcecode', pygments_directive)213214215def create_translator(link_style):216 class Translator(html4css1.HTMLTranslator):217 def visit_reference(self, node):218 refuri = node.get('refuri')219 if refuri is not None and '/' not in refuri and refuri.endswith('.txt'):220 node['refuri'] = link_style(refuri[:-4])221 html4css1.HTMLTranslator.visit_reference(self, node)222 return Translator223224225class DocumentationWriter(html4css1.Writer):226227 def __init__(self, link_style):228 html4css1.Writer.__init__(self)229 self.translator_class = create_translator(link_style)230231 def translate(self):232 html4css1.Writer.translate(self)233 # generate table of contents234 contents = self.build_contents(self.document)235 contents_doc = self.document.copy()236 contents_doc.children = contents237 contents_visitor = self.translator_class(contents_doc)238 contents_doc.walkabout(contents_visitor)239 self.parts['toc'] = self._generated_toc240241 def build_contents(self, node, level=0):242 sections = []243 i = len(node) - 1244 while i >= 0 and isinstance(node[i], nodes.section):245 sections.append(node[i])246 i -= 1247 sections.reverse()248 toc = []249 for section in sections:250 try:251 reference = nodes.reference('', '', refid=section['ids'][0], *section[0])252 except IndexError:253 continue254 ref_id = reference['refid']255 text = escape(reference.astext().encode('utf-8'))256 toc.append((ref_id, text))257258 self._generated_toc = [('#%s' % href, caption) for href, caption in toc]259 # no further processing260 return []261262263def generate_documentation(data, link_style):264 writer = DocumentationWriter(link_style)265 data = data.replace('[[list_of_filters]]', LIST_OF_FILTERS)\266 .replace('[[list_of_tests]]', LIST_OF_TESTS)\267 .replace('[[list_of_loaders]]', LIST_OF_LOADERS)\268 .replace('[[list_of_baseloaders]]', LIST_OF_BASELOADERS)\269 .replace('[[environment_doc]]', ENVIRONMENT_DOC)\270 .replace('[[changelog]]', CHANGELOG)271 parts = publish_parts(272 data,273 writer=writer,274 settings_overrides={275 'initial_header_level': 2,276 'field_name_limit': 50,277 }278 )279 return {280 'title': parts['title'].encode('utf-8'),281 'body': parts['body'].encode('utf-8'),282 'toc': parts['toc']283 }284285286def handle_file(filename, fp, dst, preproc):287 now = datetime.now()288 title = os.path.basename(filename)[:-4]289 content = fp.read().decode('utf-8')290 suffix = not preproc and '.html' or ''291 parts = generate_documentation(content, (lambda x: './%s%s' % (x, suffix)))292 result = file(os.path.join(dst, title + '.html'), 'w')293 c = dict(parts)294 c['style'] = PYGMENTS_FORMATTER.get_style_defs('.syntax')295 c['generation_date'] = now296 c['file_id'] = title297 if preproc:298 tmpl = PREPROC_TEMPLATE299 else:300 tmpl = FULL_TEMPLATE301 result.write(tmpl.render(c).encode('utf-8'))302 result.close()303304305def run(dst, preproc, sources=(), handle_file=handle_file):306 path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'src'))307 if not sources:308 sources = [os.path.join(path, fn) for fn in os.listdir(path)]309 for fn in sources:310 if not os.path.isfile(fn):311 continue312 print 'Processing %s' % fn313 f = open(fn)314 try:315 handle_file(fn, f, dst, preproc)316 finally:317 f.close()318319320def main(dst='html/', preproc=False, *sources):321 run(os.path.realpath(dst), str(preproc).lower() == 'true', sources)322323324if __name__ == '__main__':325 main(*sys.argv[1:])
added:docs/index.rst+19 added
1.. Jinja2 documentation master file, created by sphinx-quickstart on Sun Apr 27 21:42:41 2008.2 You can adapt this file completely to your liking, but it should at least3 contain the root `toctree` directive.45Welcome to Jinja2's documentation!6==================================78Contents:910.. toctree::11 :maxdepth: 21213Indices and tables14==================1516* :ref:`genindex`17* :ref:`modindex`18* :ref:`search`19
added:docs/Makefile+70 added
1# Makefile for Sphinx documentation2#34# You can set these variables from the command line.5SPHINXOPTS =6SPHINXBUILD = sphinx-build7PAPER =89# Internal variables.10PAPEROPT_a4 = -D latex_paper_size=a411PAPEROPT_letter = -D latex_paper_size=letter12ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .1314.PHONY: help clean html web pickle htmlhelp latex changes linkcheck1516help:17 @echo "Please use \`make <target>' where <target> is one of"18 @echo " html to make standalone HTML files"19 @echo " pickle to make pickle files (usable by e.g. sphinx-web)"20 @echo " htmlhelp to make HTML files and a HTML help project"21 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"22 @echo " changes to make an overview over all changed/added/deprecated items"23 @echo " linkcheck to check all external links for integrity"2425clean:26 -rm -rf _build/*2728html:29 mkdir -p _build/html _build/doctrees30 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html31 @echo32 @echo "Build finished. The HTML pages are in _build/html."3334pickle:35 mkdir -p _build/pickle _build/doctrees36 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle37 @echo38 @echo "Build finished; now you can process the pickle files or run"39 @echo " sphinx-web _build/pickle"40 @echo "to start the sphinx-web server."4142web: pickle4344htmlhelp:45 mkdir -p _build/htmlhelp _build/doctrees46 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp47 @echo48 @echo "Build finished; now you can run HTML Help Workshop with the" \49 ".hhp project file in _build/htmlhelp."5051latex:52 mkdir -p _build/latex _build/doctrees53 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex54 @echo55 @echo "Build finished; the LaTeX files are in _build/latex."56 @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \57 "run these through (pdf)latex."5859changes:60 mkdir -p _build/changes _build/doctrees61 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes62 @echo63 @echo "The overview file is in _build/changes."6465linkcheck:66 mkdir -p _build/linkcheck _build/doctrees67 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck68 @echo69 @echo "Link check complete; look for any errors in the above output " \70 "or in _build/linkcheck/output.txt."