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
Provenance
- Commit
083ae16- Tree
fcf9405- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c9705c2
32 files changed+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
1-body {2- background-color: #333;3- margin: 0;4- padding: 0;5- font-family: 'Georgia', serif;6- font-size: 15px;7- color: #111;8-}9-10-#content {11- background-color: white;12- background-image: url(watermark.png);13- padding: 10px;14- margin: 25px;15- border: 4px solid #ddd;16-}17-18-h1 {19- margin: 0;20- padding: 0;21- height: 80px;22- background-image: url(jinjabanner.png);23- background-repeat: no-repeat;24-}25-26-h1 span {27- display: none;28-}29-30-h2.subheading {31- margin: -55px 0 35px 200px;32- font-weight: normal;33- font-size: 30px;34- color: #444;35-}36-37-h2.plain {38- margin: 0;39-}40-41-#jinjalogo {42- background-image: url(jinjalogo.png);43- background-repeat: no-repeat;44- width: 400px;45- height: 160px;46-}47-48-#contentwrapper {49- max-width: 700px;50- padding: 0 0 20px 18px;51-}52-53-#contentwrapper h3,54-#contentwrapper h3 a {55- color: #b41717;56- font-size: 26px;57- margin: 20px 0 0 -5px;58-}59-60-#contentwrapper h4,61-#contentwrapper h4 a {62- color: #b41717;63- font-size: 20px;64- margin: 20px 0 0 0;65-}66-67-table.docutils {68- border-collapse: collapse;69- border: 2px solid #aaa;70- margin: 0.5em 1.5em 0.5em 1.5em;71-}72-73-table.docutils td {74- padding: 2px;75- border: 1px solid #ddd;76-}77-78-p, li, dd, dt, blockquote {79- color: #333;80-}81-82-p {83- line-height: 150%;84- margin-bottom: 0;85- margin-top: 10px;86- text-align: justify;87-}88-89-hr {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-}97-98-dl {99- margin-left: 10px;100-}101-102-li, dt {103- margin-top: 5px;104-}105-106-dt {107- font-weight: bold;108-}109-110-th {111- text-align: left;112- padding: 3px;113- background-color: #f2f2f2;114-}115-116-a {117- color: #b41717;118-}119-120-a:hover {121- color: #444;122-}123-124-pre {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-}132-133-tt {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-}140-141-cite {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-}148-149-div.admonition {150- margin: 10px 0 10px 0;151- padding: 10px;152- border: 1px solid #ccc;153- background-color: #f8f8f8;154-}155-156-div.admonition p.admonition-title {157- margin: -3px 0 5px 0;158- font-weight: bold;159- color: #b41717;160- font-size: 16px;161-}162-163-div.admonition p {164- margin: 0 0 0 40px;165-}166-167-#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-}176-177-#toc h2 {178- font-size: 20px;179- margin: 0 0 10px 0;180- padding: 0;181- color: #444;182-}183-184-#toc ul {185- margin: 0 0 0 30px;186- padding: 0;187-}188-189-#toc ul + h2 {190- margin-top: 10px;191-}192-193-#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-==================2-Alternative Syntax3-==================4-5-Jinja allows some syntax customization for the block delimiters. Depending on6-the Jinja release more or less combinations are possible. The idea of an7-customizable syntax is that you can update existing templates from other8-template engines and programming languages easier and that you can replace9-the django like default delimiters which are not everybody's favorite.10-11-12-Configuring The Environment13-===========================14-15-For syntax configuration there are six arguments in the environment which16-are the first six for convenience. Thus those two snippets do the same:17-18-.. sourcecode:: python19-20- 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- )28-29- env = Environment('{%', '%}', '{{', '}}', '{#', '#]')30-31-32-Ruby Like Syntax33-----------------34-35-Here an example configuration for Ruby-like syntax:36-37-.. sourcecode:: python38-39- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')40-41-An example template then looks like this:42-43-.. sourcecode:: rhtml44-45- <%# example eruby like configuration for Jinja %>46- <ul>47- <% for item in seq %>48- <li><%= item %></li>49- <% endfor %>50- </ul>51-52-53-SGML Comment Syntax54--------------------55-56-Here an example configuration that uses SGML comments to hide the57-processing instructions. This can be useful if you work with an WYSIWYG58-designer:59-60-.. sourcecode:: python61-62- env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')63-64-.. sourcecode:: html65-66- <!--# example SGML comment configuration for Jinja -->67- <ul>68- <!-- for item in seq -->69- <li>${item}</li>70- <!-- endfor -->71- </ul>72-73-74-Parenthesis Balancing75----------------------76-77-Starting with Jinja 1.1 it's possible to use the block delimiter as a token78-in the expression. That means that you can use small delimiters like single79-braces 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 need81-Jinja 1.1 or higher.82-83-84-Block / Variable Tag Unification85-================================86-87-If variable end and start tags are `None` or look the same as block tags and88-you'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 block90-first and continue treating it as variable block if there is no known91-directive for that name. Example:92-93-.. sourcecode:: python94-95- env = Environment('{', '}', None, None, '{*', '*}')96-97-This now allows smarty like templates:98-99-.. sourcecode:: smarty100-101- {* 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}107-108-This feature however can cause strange looking templates because there is no109-visible difference between blocks and variables.deleted:docs/src/api.txt-315 removed
1-=======================2-Context and Environment3-=======================4-5-The two central objects in Jinja are the `Environment` and `Context`. Both6-are designed to be subclassed by applications if they need to extend Jinja.7-8-Environment9-===========10-11-The initialization parameters are already covered in the `Quickstart`_ thus12-not repeated here.13-14-But beside those configurable instance variables there are some functions used15-in the template evaluation code you may want to override:16-17-**def** `parse` *(source, filename)*:18-19- 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.22-23-**def** `lex` *(source, filename)*:24-25- 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**30-31-**def** `from_string` *(source)*:32-33- 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.36-37-**def** `get_template` *(name)*:38-39- Load a template from a loader. If the template does not exist, you will40- get a `jinja.exceptions.TemplateNotFound` exception.41-42-**def** `to_unicode` *(self, value)*:43-44- 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.47-48- Also `None` is converted into an empty string per default.49-50-**def** `get_translator` *(self, context)*:51-52- 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`_.57-58- If you don't provide a translator a default one is used to switch59- between singular and plural forms.60-61- Have a look at the `i18n`_ section for more information.62-63-**def** `get_translations` *(self, name)*:64-65- Get the translations for the template `name`. Only works if a loader66- is present. See the `i18n`_ section for more details.67-68-**def** `get_translations_for_string` *(self, string)*:69-70- 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.73-74-**def** `apply_filters` *(self, value, context, filters)*:75-76- 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:81-82- .. sourcecode:: python83-84- [('escape', ()), ('replace', (u'a', u'b'))]85-86- 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.90-91- **Warning** this is a Jinja internal method. The actual implementation92- and function signature might change.93-94-**def** `perform_test` *(self, context, testname, args, value, invert)*:95-96- Like `apply_filters` you usually don't override this one. It's the97- callback function for tests (``foo is bar`` / ``foo is not bar``).98-99- 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.103-104- Missing tests should raise a `TestNotFound` exception.105-106- **Warning** this is a Jinja internal method. The actual implementation107- and function signature might change.108-109-**def** `get_attribute` *(self, obj, attribute)*:110-111- Get `attribute` from the object provided. The default implementation112- performs security tests.113-114- **Warning** this is a Jinja internal method. The actual implementation115- and function signature might change.116-117-**def** `get_attributes` *(self, obj, attributes)*:118-119- Get some attributes from the object. If `attributes` is an empty120- sequence the object itself is returned unchanged.121-122-**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.128-129- The default implementation performs some security checks.130-131- **Warning** this is a Jinja internal method. The actual implementation132- and function signature might change.133-134-**def** `call_function_simple` *(self, f, context)*:135-136- Like `call_function` but without arguments.137-138- **Warning** this is a Jinja internal method. The actual implementation139- and function signature might change.140-141-**def** `finish_var` *(self, value, ctx)*:142-143- Postprocess a variable before it's sent to the template.144-145- **Warning** this is a Jinja internal method. The actual implementation146- and function signature might change.147- 148-.. admonition:: Note149-150- The Enviornment class is defined in `jinja.environment.Environment`151- but imported into the `jinja` package because it's often used.152-153-Context154-=======155-156-Jinja wraps the variables passed to the template in a special class called a157-context. This context supports variables on multiple layers and lazy (deferred)158-objects. Often your application has a request object, database connection159-object or something similar you want to access in filters, functions etc.160-161-The default context object is defined in `jinja.datastructure`. If you want162-to provide your own context object always subclass the default one. This163-ensures that the class continues working after Jinja upgrades.164-165-Beacause of that you can easily subclass a context to add additional variables166-or to change the way it behaves.167-168-**def** `pop` *(self)*:169-170- Pop the outermost layer and return it.171-172-**def** `push` *(self, data=None)*:173-174- Push a dict to the stack or an empty layer.175-176- Has to return the pushed object.177-178-**def** `to_dict` *(self)*:179-180- Flatten the context and convert it into a dict.181-182-**def** `__getitem__` *(self, name)*:183-184- Resolve an item. Per default this also resolves `Deferred` objects.185-186-**def** `__setitem__` *(self, name, value)*:187-188- Set an item in the outermost layer.189-190-**def** `__delitem__` *(self, name)*:191-192- Delete an item in the outermost layer. Do not raise exceptions if193- the value does not exist.194-195-**def** `__contains__` *(self, name)*:196-197- Return `True` if `name` exists in the context.198-199-**attribute** `cache`:200-201- 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.204-205-**attribute** `translate_func`:206-207- 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.210-211-.. admonition:: Note212-213- 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:216-217- `globals`:218- 219- The reference to the global namespace of the environment.220- It's the lowest namespace on the stack and thus immutable221-222- `initial`:223-224- 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.228-229- `current`:230-231- The reference to the current active namespace. When the232- context is initialized this automatically points to an233- empty namespace.234-235- 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.239-240- This is done in order to keep the namespace clean.241-242- 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`.247-248- Since you cannot reproduce completely the same semantics in python249- and the C API there are some things you should keep in mind:250-251- - 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.254-255- - `globals`, `current` and `initial` are read only attributes that256- map to layers on the stack which you can of course modify.257-258-259-Exceptions260-==========261-262-During parsing and evaluation Jinja raises a couple of Jinja specific263-exceptions. All of those exceptions are defined in the `jinja.exceptions`264-module and are subclasses of the `TemplateError` class defined there.265-266-Here a list of exceptions that could occur:267-268-`SecurityException`:269-270- 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.273-274- If however the environment is configured to not silently fail it275- could happen that this exception reaches the application.276-277-`FilterNotFound`:278-279- 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.282-283-`FilterArgumentError`:284-285- 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.287-288-`TestNotFound`:289-290- 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.293-294-`TestArgumentError`:295-296- 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.298-299-`TemplateNotFound`:300-301- Raised if a template does not exist. Subclass of `IOError` too.302-303-`TemplateSyntaxError`:304-305- Subclass of `SyntaxError` and used to indicate an syntax error.306-307-`TemplateRuntimeError`:308-309- Generic runtime error exception which can occour at various places.310-311-312-.. _i18n: i18n.txt313-.. _translators: translators.txt314-.. _Quickstart: devintro.txt315-.. _gettext documentation: http://docs.python.org/lib/module-gettext.htmldeleted:docs/src/builtins.txt-228 removed
1-===================================2-Filters, Tests and Helper Functions3-===================================4-5-This part of the documentation lists the filter-, test- and helper functions6-you can use in templates.7-8-9-Filters10-=======11-12-In the examples above you might have noticed the pipe symbols. Pipe symbols tell13-the engine that it has to apply a filter on the variable. Here is a small example:14-15-.. sourcecode:: jinja16-17- {{ variable|replace('foo', 'bar')|escape }}18-19-If you want, you can also put whitespace between the filters.20-21-This will look for a variable `variable`, pass it to the filter `replace`22-with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter23-`escape` that automatically XML-escapes the value. The `e` filter is an alias for24-`escape`. Here is the complete list of supported filters:25-26-[[list_of_filters]]27-28-.. admonition:: note29-30- *Jinja 1.0 and 1.1 notice*31-32- 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:35-36- .. sourcecode:: jinja37-38- correct:39- {{ (foo|filter) + (bar|filter) }}40- wrong:41- {{ foo|filter + bar|filter }}42-43- correct:44- {{ (foo|filter).attribute }}45- wrong:46- {{ foo|filter.attribute }}47-48- 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``.50-51-*new in Jinja 1.1*:52-53-Because the application can provide additional filters you can get a documentation54-of all the provided filters by calling ``debug.filters()``:55-56-.. sourcecode:: jinja57-58- {{ debug.filters() }}59- -> returns a plain text representation of all the filters60-61- {{ debug.filters(False) }}62- -> same as above but without the builtin ones.63-64-Tests65-=====66-67-You can use the `is` operator to perform tests on a value:68-69-.. sourcecode:: jinja70-71- {{ 42 is numeric }} -> true72- {{ "foobar" is numeric }} -> false73- {{ 'FOO' is upper }} -> true74-75-These tests are especially useful when used in `if` conditions.76-77-[[list_of_tests]]78-79-*new in Jinja 1.1*:80-81-Because the application can provide additional tests you can get a documentation82-of all the provided tests by calling ``debug.tests()``:83-84-.. sourcecode:: jinja85-86- {{ debug.tests() }}87- -> returns a plain text representation of all the tests88-89- {{ debug.tests(False) }}90- -> same as above but without the builtin ones.91-92-*new in Jinja 1.2*:93-94-If a test function expects one or no argument you can leave out the parentheses.95-Previously this was only possible for text functions without arguments:96-97-.. sourcecode:: jinja98-99- {{ foo is matching @/\s+/ }}100- is the same as101- {{ foo is matching(@/\s+/) }}102-103-104-Global Functions105-================106-107-Test functions and filter functions live in their own namespace. Global108-functions not. They behave like normal objects in the context. Beside the109-functions added by the application or framewhere there are two functions110-available per default:111-112-`range`113- 114- Works like the python `range function`_ just that it doesn't support115- ranges greater than ``1000000``.116-117-`debug`118-119- Function that outputs the contents of the context.120-121-`lipsum`122-123- Generate some paragraphs of random text:124-125- .. sourcecode:: jinja126-127- {{ lipsum(5) }}128- five html paragraphs129-130- {{ lipsum(2, False) }}131- two ascii only paragraphs132-133- Per default a paragraph is between 20 and 100 words long. You can134- override this default with the third and fourth parameter:135-136- .. sourcecode:: jinja137-138- {{ lipsum(10, True, 50, 200) }}139- generate 10 HTML paragraphs between 50 and 200 words.140-141- *new in Jinja 1.1*142-143-`watchchanges`144-145- Jinja does not provide an django like ``{% ifchanged %}`` tag. As146- replacement for this tag there is a special function in the namespace147- called `watchchanges`.148-149- You can use it like this:150-151- .. sourcecode:: html+jinja152-153- {% 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 %}158-159- 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`.162-163- 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`.167-168- If you want to observe more than one attribute you can provide pairs:169-170- .. sourcecode:: html+jinja171-172- {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}173- ...174- {% endfor %}175-176- Note that if you want to watch two first level attributes you have to177- either use the list syntax `[]` or add a colon:178-179- .. sourcecode:: html+jinja180-181- {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}182- ...183- {% endfor %}184-185- otherwise Jinja cannot differ between a pair of parentheses to group186- expressions or the sequence syntax.187-188- If you don't provide any arguments the value of the variable itself189- is checked.190-191- *new in Jinja 1.1*192-193-`rendertemplate`194-195- 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.199-200- *new in Jinja 1.1*201-202-203-Global Constants204-================205-206-Jinja provides some special variables which cannot be overridden in templates.207-Those are not affected by the variable lookup:208-209- `_`, `true`, `false`, `none`, `undefined`210-211-You cannot use those names for your own variables or macros. It's however no212-problem to have blocks with that name.213-214-**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 %}`216-or in a for loop. While overriding `true`, `false` etc just caused nothing217-overriding the translation marker `_` would crash the translation interface.218-If you want to use `_` for unpacking in for loops (eg. skipping items) you219-have to give it a proper name:220-221-.. sourcecode:: jinja222-223- {% for key, ignore in mydict|dictsort %}224- {{ key|e }}225- {% endfor %}226-227-228-.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000deleted:docs/src/changelog.txt-1 removed
1-[[changelog]]deleted:docs/src/debugging.txt-32 removed
1-===================2-Debugging Templates3-===================4-5-In order to keep templates debuggable you have to do some additional work on6-the application side. The traceback module that comes with python currently7-does not support the `__loader__` hook which is used by Jinja to provide8-templates. Although the import system was implemented three Python versions9-ago the default traceback system still doesn't support it.10-11-However most of the extended web development traceback modules have support12-for `__loader__`. Either directly or via the linecache module:13-14-- `Werkzeug Debugging Middleware`_15-- `Django`_16-- `cgitb`_17-- `EvalException`_18-19-To enable debugging you have to use one of those debugging systems or20-implement your own one with support for `__loader__`.21-22-The python implementation of the jinja debugger can only translate the first23-exception in a traceback which can lead to problematic results. If you have24-the extended debugger c extension compiled (default on unix systems but only25-available on Windows if you have a VisualStudio 2003 installation) all frames26-in the traceback will point to the correct linenumbers of the templates.27-28-29-.. _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.htmldeleted:docs/src/designerdoc.txt-565 removed
1-======================2-Designer Documentation3-======================4-5-This part of the Jinja documentaton is meant for template designers.6-7-Basics8-======9-10-The Jinja template language is designed to strike a balance between content11-and application logic. Nevertheless you can use a python like statement12-language. You don't have to know how Python works to create Jinja templates,13-but if you know it you can use some additional statements you may know from14-Python.15-16-Here is a small example template:17-18-.. sourcecode:: html+jinja19-20- <!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>32-33- <h1>My Webpage</h1>34- {{ variable }}35- </body>36- </html>37-38-This covers the default settings. The application developer might have changed39-the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar. This40-documentation just covers the default values.41-42-A variable looks like ``{{ foobar }}`` where foobar is the variable name. Inside43-of statements (``{% some content here %}``) variables are just normal names44-without the braces around it. In fact ``{{ foobar }}`` is just an alias for45-the statement ``{% print foobar %}``.46-47-Variables are coming from the context provided by the application. Normally there48-should be a documentation regarding the context contents but if you want to know49-the content of the current context, you can add this to your template:50-51-.. sourcecode:: html+jinja52-53- <pre>{{ debug()|e }}</pre>54-55-A context isn't flat which means that each variable can has subvariables, as long56-as it is representable as python data structure. You can access attributes of57-a variable using the dot and bracket operators. The following examples show58-this:59-60-.. sourcecode:: jinja61-62- {{ 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 }}69-70-*new in Jinja 1.2*: You can now use django like attributes for integer71-indices. Thus ``{{ foo.0 }}`` is equivalent to ``{{ foo[0] }}``.72-73-74-Loops75-=====76-77-To iterate over a sequence, you can use the `for` loop. It basically looks like a78-normal Python `for` loop and works pretty much the same:79-80-.. sourcecode:: html+jinja81-82- <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>90-91-*Important* Contrary to Python is the optional `else` block only92-executed if there was no iteration because the sequence was empty.93-94-Inside of a `for` loop block you can access some special variables:95-96-+----------------------+----------------------------------------+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-+----------------------+----------------------------------------+122-123-Loops also support recursion. Let's assume you have a sitemap where each item124-might have a number of child items. A template for that could look like this:125-126-.. sourcecode:: html+jinja127-128- <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>135-136-What happens here? Basically the first thing that is different to a normal137-loop is the additional ``recursive`` modifier in the `for`-loop declaration.138-It tells the template engine that we want recursion. If recursion is enabled139-the special `loop` variable is callable. If you call it with a sequence it will140-automatically render the loop at that position with the new sequence as argument.141-142-Cycling143-=======144-145-Sometimes you might want to have different text snippets for each row in a list,146-for example to have alternating row colors. You can easily do this by using the147-``{% cycle %}`` tag:148-149-.. sourcecode:: html+jinja150-151- <ul id="messages">152- {% for message in messages %}153- <li class="{% cycle 'row1', 'row2' %}">{{ message|e }}</li>154- {% endfor %}155- </ul>156-157-Each time Jinja encounters a `cycle` tag it will cycle through the list158-of given items and return the next one. If you pass it one item jinja assumes159-that this item is a sequence from the context and uses this:160-161-.. sourcecode:: html+jinja162-163- <li style="color: {% cycle rowcolors %}">...</li>164-165-Conditions166-==========167-168-Jinja supports Python-like `if` / `elif` / `else` constructs:169-170-.. sourcecode:: jinja171-172- {% 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 %}179-180-If the user is active the first block is rendered. If not and the user was181-deleted the second one, in all other cases the third one.182-183-You can also use comparison operators:184-185-.. sourcecode:: html+jinja186-187- {% if amount < 0 %}188- <span style="color: red">{{ amount }}</span>189- {% else %}190- <span style="color: black">{{ amount }}</span>191- {% endif %}192-193-.. admonition:: Note194-195- 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.200-201-Literals202-========203-204-For most of the builtin python types, literals exist in Jinja. The following205-table shows which syntax elements are supported:206-207- ======================= ===================================================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- ======================= ===================================================225-226-.. admonition:: Common Pitfalls227-228- 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- 233-234-Operators235-=========236-237-Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can238-can use expressions. In expressions you can use any of the following operators:239-240- ======= ===================================================================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- ======= ===================================================================271-272-Note that there is no support for any bit operations or something similar.273-274-* 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)``.278-279-280-With Jinja 1.2 onwards it's possible to replace basic if/else blocks with the281-inline `if` / `else` expression. The following two examples evaluate to the282-same:283-284-.. sourcecode:: jinja285-286- {{ "something" if expr else "otherthing" }}287-288- {% if expr %}something{% else %}otherthing{% endif %}289-290-291-Boolean Values292-==============293-294-In If-Conditions Jinja performs a boolean check. All empty values (eg: empty295-lists ``[]``, empty dicts ``{}`` etc) evaluate to `false`. Numbers that are296-equal to `0`/`0.00` are considered `false` too. The boolean value of other297-objects depends on the behavior the application developer gave it. Usually298-items are `true`.299-300-Here some examples that should explain it:301-302-.. sourcecode:: jinja303-304- {% if [] %}305- will always be false because it's an empty list306-307- {% if {} %}308- false too.309-310- {% if ['foo'] %}311- this is true. Because the list is not empty.312-313- {% if "foobar" %}314- this is also true because the string is not empty.315-316-Slicing317-=======318-319-Some objects support slicing operations. For example lists:320-321-.. sourcecode:: jinja322-323- {% for item in items[:5] %}324- This will only iterate over the first 5 items of the list325-326- {% for item in items[5:10] %}327- This will only iterate from item 5 to 10.328-329- {% for item in items[:10:2] %}330- This will only yield items from start to ten and only returing331- even items.332-333-For more informations about slicing have a look at the `slicing chapter`_334-in the "Dive into Python" e-book.335-336-Macros337-======338-339-If you want to use a partial template in more than one place, you might want to340-create a macro from it:341-342-.. sourcecode:: html+jinja343-344- {% macro show_user user %}345- <h1>{{ user.name|e }}</h1>346- <div class="text">347- {{ user.description }}348- </div>349- {% endmacro %}350-351-Now you can use it from everywhere in the code by passing it an item:352-353-.. sourcecode:: jinja354- 355- {% for user in users %}356- {{ show_user(user) }}357- {% endfor %}358-359-You can also specify more than one value:360-361-.. sourcecode:: html+jinja362-363- {% 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 %}369-370- {{ show_dialog('Warning', 'something went wrong i guess') }}371-372-*Improvements in Jinja 1.1*:373-374- Starting with Jinja 1.1 it's possible to use optional parentheses375- around the macro arguments:376-377- .. sourcecode:: html+jinja378-379- {% macro foo(a, b) %}380- ...381- {% endmacro %}382-383- Additionally extra arguments passed to the macro end up in the384- special variable `varargs`. So you can have a macro like this:385-386- .. sourcecode:: html+jinja387-388- {% 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 %}397-398- {{ make_list("John", "Jane", "Marcus", "Heinrich") }}399-400- If a macro parameter is called `varargs` the additional extra401- arguments are not accessible.402-403-For information regarding the visibility of macros have a look at the404-`Scopes and Variable Behavior`_ section.405-406-407-Extended Macro Call408-===================409-410-*new in Jinja 1.1*411-412-Jinja 1.1 adds a new special tag that you can use to pass some evaluable413-template code to a macro. Here an example macro that uses the features of414-the ``{% call %}`` tag:415-416-.. sourcecode:: html+jinja417-418- {% macro dialog title %}419- <div class="dialog">420- <h3>{{ title }}</h3>421- <div class="text">422- {{ caller() }}423- </div>424- </div>425- {% endmacro %}426-427-Called the normal way `caller` will be undefined, but if you call it428-using the new `{% call %}` tag you can pass it some data:429-430-.. sourcecode:: html+jinja431-432- {% call dialog('Hello World') %}433- This is an example dialog434- {% endcall %}435-436-Now the data wrapped will be inserted where you put the `caller` call.437-438-If you pass `caller()` some keyword arguments those are added to the439-namespace of the wrapped template data:440-441-.. sourcecode:: html+jinja442-443- {% macro makelist items %}444- <ul>445- {%- for item in items %}446- <li>{{ caller(item=item) }}</li>447- {%- endfor %}448- </ul>449- {%- endmacro %}450-451- {% call makelist([1, 2, 3, 4, 5, 6]) -%}452- [[{{ item }}]]453- {%- endcall %}454-455-This will then produce this output:456-457-.. sourcecode:: html458-459- <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>467-468-469-Template Inclusion470-==================471-472-You can load another template at a given position using ``{% include %}``.473-Usually it's a better idea to use inheritance but if you for example want to474-load macros, `include` works better than `extends`:475-476-.. sourcecode:: jinja477-478- {% include "myhelpers.html" %}479- {{ my_helper("foo") }}480-481-If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now482-use it from the template as shown above.483-484-Please keep in mind that include does not render the template indenpendently485-but includes the processing instructions into the current template. Thus if the486-included template contains a ``{% extends %}`` tag it also affects the current487-template.488-489-This is intended because it makes it possible to include macros from other490-templates.491-492-*new in Jinja 1.1* you can now render an included template to a string that is493-evaluated in an indepdendent environment by calling `rendertemplate`. See the494-documentation for this function in the `builtins`_ documentation.495-496-497-Filtering Blocks498-================499-500-Sometimes it could be a good idea to filter a complete block of text. For501-example, if you want to escape some html code:502-503-.. sourcecode:: jinja504-505- {% filter escape %}506- <html>507- <code>goes here</code>508- </html>509- {% endfilter %}510-511-Of course you can chain filters too:512-513-.. sourcecode:: jinja514-515- {% filter lower|escape %}516- <B>SOME TEXT</B>517- {% endfilter %}518-519-returns ``"<b>some text</b>"``.520-521-522-Defining Variables523-==================524-525-You can also define variables in the namespace using the ``{% set %}`` tag:526-527-.. sourcecode:: jinja528-529- {% set foo = 'foobar' %}530- {{ foo }}531-532-This should ouput ``foobar``.533-534-For information regarding the visibility of variables have a look at the535-`Scopes and Variable Behavior`_ section.536-537-538-Reserved Keywords539-=================540-541-Jinja has some keywords you cannot use a variable names. This limitation542-exists to make templates look coherent. Syntax highlighters won't mess things543-up and you won't have the situation that some names work depending on the544-context.545-546-The following keywords exist and cannot be used as identifiers:547-548- `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`552-553-If you want to use such a name you have to prefix or suffix it or use554-alternative names:555-556-.. sourcecode:: jinja557-558- {% for macro_ in macros %}559- {{ macro_('foo') }}560- {% endfor %}561-562-563-.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice564-.. _Scopes and Variable Behavior: scopes.txt565-.. _builtins: builtins.txtdeleted:docs/src/devintro.txt-190 removed
1-====================2-Developer Quickstart3-====================4-5-This part of the documentation shows you how to embed Jinja into your6-application.7-8-Starting Up9-===========10-11-Here the quickest way to create a template from a string and render it:12-13-.. sourcecode:: python14-15- from jinja import Environment16- env = Environment()17- tmpl = env.from_string('Hello {{ name }}!')18- print tmpl.render(name='John Doe')19-20-This example should output the following string after execution::21-22- Hello John Doe!23-24-If you receive an error, check if you have a typo in your code. If not, have25-a look at the `installation`_ page for troubleshooting.26-27-Basically the important method on a template is the `render` method. It28-takes either a dict or keyword arguments. All keyword arguments appear29-in the template as variables.30-31-So these two snippets do the same:32-33-.. sourcecode:: python34-35- tmpl.render(36- knights='we say nih',37- spam='and eggs'38- )39-40-.. sourcecode:: python41-42- tmpl.render({43- 'knights': 'we say nih',44- 'spam': 'and eggs'45- })46-47-The Environment48-===============49-50-[[environment_doc]]51-52-The environment provides the following useful functions and properties in53-addition to the initialization values:54-55-=========================== ==================================================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-=========================== ==================================================73-74-There are also some internal functions on the environment used by the template75-evaluation code to keep it sandboxed.76-77-Undefined Values78-================79-80-If a template designer tries to access a not defined value the return value81-will be the `undefined_singleton` specified in the environment. The default82-one is the `SilentUndefined` which fails in no case. Additionally there is83-a special undefined type called the `ComplainingUndefined` which is located84-in the `jinja.datastructure` module. It will raise exceptions when compared85-with other types, or when rendered.86-87-Theoretically 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 cover90-the basic use cases. The `Undefined` object in that module exists for91-backwards compatibility and is an alias for `SilentUndefined`.92-93-To create your own undefined singleton do something like this:94-95-.. sourcecode:: jinja96-97- from jinja.datastructure import AbstractUndefinedType, make_undefined98-99- class MyUndefinedType(AbstractUndefindedType):100- __slots__ = ()101-102- def __iter__(self):103- return iter(int, 0)104-105- def __reduce__(self):106- return 'MyUndefined'107-108- MyUndefined = make_undefined(MyUndefinedType)109-110-The only thing you have to do is to override `__reduce__` so that it returns111-the name of the singleton instance and create the instance using112-`make_undefined`. Everything else is up to you. Note that currently attributes113-on undefined objects are available in the Jinja layer too which however114-will change in one of the next Jinja versions. So if you put a `foo` attribute115-on your undefined singleton you will be able to do ``{{ undefined.foo }}``116-by now but certainly not in the future.117-118-This limitation currently exists because undefined is treated as normal object119-and thus affected by normal getattr calls.120-121-122-Automatic Escaping123-==================124-125-Jinja provides a way for automatic escaping, but we do not recommend using it.126-Because Jinja was designed as multi purpose template engine there are some127-issues with automatic escaping. For example filters don't deal with markup128-data. Also you can easily bypass the automatic escaping so it's not something129-you can expect to "just work". Also there is a huge overhead when escaping130-everything.131-132-The best idea is to think about which data already contains html, which will133-probably contain (eg: every user input, etc) etc. And live with self escaping.134-135-That's usually a much better idea.136-137-138-Loading Templates From Files139-============================140-141-Loading templates from a string is always a bad idea. It doesn't allow template142-inheritance and is also slow since it parses and compiles the template again143-and again whereas loaders can cache the template code.144-145-All you have to do is to define a loader and use the `get_template` function.146-147-.. sourcecode:: python148-149- from jinja import Environment, FileSystemLoader150- env = Environment(loader=FileSystemLoader('templates'))151- tmpl = env.get_template('index.html')152- print tmpl.render(name='John Doe')153-154-This tells jinja to look for templates in the ``templates`` folder. It's a155-better idea to use an absolute path here though. For a list of supported156-loaders or how to write your own, head over to the `loader`_ documentation.157-158-Adding Filters159-==============160-161-If you want to add additional filters to the environment, the best way is to162-modify the ``filters`` attribute and not to pass a dict to the environment.163-If you pass it a dict it will not include the default filters!164-165-.. sourcecode:: python166-167- from mylib import my_cool_filter168- env.filters['mycoolfilter'] = my_cool_filter169-170-Writing filter functions is explained in the `filter development`_ section.171-172-Adding Tests173-============174-175-Adding additional tests works analogous to filters:176-177-.. sourcecode:: python178-179- from mylib import my_cool_test180- env.tests['mycooltest'] = my_cool_test181-182-Writing tests is explained in the `test development`_ section.183-184-185-.. _installation: installation.txt186-.. _context documentation: contextenv.txt187-.. _loader: loaders.txt188-.. _translators: translators.txt189-.. _filter development: filters.txt190-.. _test development: tests.txtdeleted:docs/src/devrecipies.txt-139 removed
1-=======================2-Recipies For Developers3-=======================4-5-Here some recipies for application developers.6-7-8-Automagic Template Variables9-============================10-11-Python allows some magic stack manipulation which can be used to12-pass variables to templates automatically. It's not a recommended13-way to pass variables to templates but it can be useful for some14-small generation scripts etc.15-16-Just subclass the environment and add an `autorender` function like17-this:18-19-.. sourcecode:: python20-21- import sys22- from jinja import Environment23-24- class AutoEnvironment(Environment):25-26- def autorender(self, template):27- tmpl = self.get_template(template)28- return tmpl.render(sys._getframe(1).f_locals)29-30-You can use it now like this:31-32-.. sourcecode:: python33-34- def foo():35- seq = range(10)36- foo = "blub"37- return env.autorender('foo.html')38-39-In the template you can now access the local variables `seq` and `foo`.40-41-42-Using Django Filters with Jinja43-===============================44-45-If you use Jinja in django and want to use some of the filters that46-are part of the django core you can use this snippet:47-48-.. sourcecode:: python49-50- 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_factory56-57-You can now convert django filters for jinja using `convert_filter`. *Note*:58-Django only supports one filter argument. Because of this limitation you59-shouldn't pass it more arguments than it accepts. Because django uses some60-introspection to find out if a filter accepts an argument weird things can61-happen if you call it with an incompatible argument count.62-63-You can now register django filters for a jinja environment:64-65-.. sourcecode:: python66-67- from django.template.defaultfilters import date68- env.filters['date'] = convert_django_filter(date)69-70-And use it:71-72-.. sourcecode:: jinja73-74- {{ entry.pub_date|date }}75-76-Also keep in mind that Jinja knows about keywords, thus you cannot have a filter77-that is called `pluralize` for example.78-79-Such a conversion function is also part of the djangosupport module which was80-introduced in Jinja 1.2. It's explained on the `Framework Integration`_ page.81-82-83-Using Jinja in Django84-=====================85-86-.. admonition:: Note87-88- This section is more or less obsolete as of Jinja 1.2 which provides a89- djangosupport module, covered on the `Framework Integration`_ page.90-91-This snippet was contributed by Bryan McLemore. It provides a `render_to_response`92-function similar to the one shipped with django just that it uses Jinja for93-rendering. It applies the context processors on the context and consumes a94-`RequestContext`:95-96-.. sourcecode:: python97-98- from django.template.context import get_standard_processors99- from django.http import HttpResponse100- from jinja import Environment, FileSystemLoader, ChoiceLoader101- from django.conf import settings102-103- loaders = []104- for location in settings.TEMPLATE_DIRS:105- loaders.append(FileSystemLoader(location))106- env = Environment(loader=ChoiceLoader(loaders))107-108- 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))114-115-116-If you want to plug Jinja into the Django i18n system you can use this117-environment class:118-119-.. sourcecode:: python120-121- from jinja import Environment122- from django.utils.translation import gettext, ngettext123-124- class DjangoTranslator(object):125-126- def __init__(self):127- self.gettext = gettext128- self.ngettext = ngettext129-130- class DjangoEnvironment(Environment):131-132- def get_translator(self, context):133- return DjangoTranslator()134-135-Because Django uses gettext internally we can create just assign the136-ngettext and gettext functions directly to the translator class.137-138-139-.. _Framework Integration: frameworks.txtdeleted:docs/src/escaping.txt-71 removed
1-=======================2-Whitespace and Escaping3-=======================4-5-This section of the documentation explains how to remove unused whitespace6-from the templates and embed raw Jinja syntax.7-8-Escaping9-========10-11-Sometimes you might want to add Jinja syntax elements into the template12-without executing them. In that case you have quite a few possibilities.13-14-For small parts this might be a good way:15-16-.. sourcecode:: jinja17-18- {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}19-20-When you have multiple elements you can use the ``raw`` block:21-22-.. sourcecode:: jinja23-24- {% raw %}25- Filtering blocks works like this in Jinja:26- {% filter escape %}27- <html>28- <code>goes here</code>29- </html>30- {% endfilter %}31- {% endraw %}32-33-34-Whitespace35-==========36-37-If the Jinja environment was created with ``trim_blocks`` set to true the38-first newline after a template tag is removed automatically (php like39-processing).40-41-Starting with `Jinja 1.1` you can also handle some whitespace rules in the42-template. If you put an minus sign (`-`) to the start or end of an block43-(for example a `for` tag), a comment or variable element you can remove44-the whitespaces after or before that block:45-46-.. sourcecode:: jinja47-48- {% for item in seq -%}49- {{ item }}50- {%- endfor %}51-52-This will yield all elements without whitespace between them because they53-are automatically removed. This of course works for other tags too:54-55-.. sourcecode:: jinja56-57- {% for user in userlist -%}58- {{ user|e -}}59- {% if not loop.last %},{% endif %}60- {%- endfor %}61-62-Note that you must not use a whitespace between the tag and the minus sign:63-64-.. sourcecode:: jinja65-66- valid:67- {%- if foo -%}...{% endif %}68-69- invalid:70-71- {% - if foo - %}...{% endif %}deleted:docs/src/filters.txt-73 removed
1-================2-Filter Functions3-================4-5-Filters are a powerful feature of Jinja taken from django which probably took6-it from UNIX. The idea is that you "pipe" a value through some filters to7-do something with it. For example convert it to upper case, escape it or8-replace a substring.9-10-Jinja comes with some builtin filters explained in the `designer documentation`_.11-12-Writing Filters13-===============14-15-A filter basically is a factory function, a function that returns another16-function. We do this because filters can get an unlimited amount of positional17-arguments and aditionally should gain access to the environment, context and18-piped value. A simple filter looks like this:19-20-.. sourcecode:: python21-22- 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 wrapped29-30-Now you have to register that filter on an environment:31-32-.. sourcecode:: python33-34- env.filters['join'] = do_join35-36-In fact this filter is already bundled so you won't see any effect. But it37-should explain how such a filter looks like. The template designer can just38-trigger the outer code (i.e. call `join` with or without arguments). The39-returned function is then processed by the jinja template engine once all40-filters are created.41-42-If you want to create filters that just operate on a string (in fact unicode43-objects) you can use the `stringfilter` decorator:44-45-.. sourcecode:: python46-47- from jinja.filters import stringfilter48-49- @stringfilter50- def do_strip(value):51- return value.strip()52-53-The wrapped function is created internally by the decorator, any positional54-arguments are forwarded to the filter function. The first argument is always55-the value already converted into a string.56-57-If you're using Jinja with django and want to use the django filters in Jinja58-have a look at the `developer recipies`_ page.59-60-*new in Jinja 1.1* additionally to the `stringfilter` decorator there is now61-a similar decorator that works exactly the same but does not convert values62-to unicode:63-64-.. sourcecode:: python65-66- from jinja.filters import simplefilter67-68- @simplefilter69- def do_add(value, to_add):70- return value + to_add71-72-.. _designer documentation: builtins.txt73-.. _developer recipies: devrecipies.txtdeleted:docs/src/frameworks.txt-247 removed
1-=====================2-Framework Integration3-=====================4-5-Starting with Jinja 1.1 it's possible to embed Jinja into some of the existing6-frameworks a lot easier. When speaking of frameworks we only refer to `Pylons`_7-which has a working implementation of the TurboGears template specification.8-9-Since the whole situation is problematic because of various reasons (kid10-specific, uses dotted names for template loading, package name prefix etc.)11-we worked around some of the problems by using pylons specific workarounds.12-13-Jinja also ships an implementation for a hypothetical template abstraction layer14-called `General Template Interface`_ which isn't implemented by any existing15-framework so far. This specification however tries to solve the problems that16-exist in Buffet.17-18-19-Buffet20-======21-22-The buffet specification proposes that templates are named in dotted names. That23-means `foo.bar` and not `foo/bar.html`. The dotted notation has the disadvantage24-that you cannot specify the filename extension. In recent pylons versions it's25-however possible to load templates with their native path too if you prefix the26-template name with a foreslash (`/foo/bar.html`). If you don't specify the27-extension it will assume `.html` for the dotted notation.28-29-Here the list of configuration values:30-31-======================= ======================================================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-======================= ======================================================69-70-All other options that start with `jinja.` are automatically forwarded to the71-environment constructor.72-73-In pylons for example you can use jinja as buffet plugin like this:74-75-Edit the `yourproject/config/middleware.py` and add this to `config.init_app`:76-77-.. sourcecode:: python78-79- config.add_template_engine('jinja', '', {80- 'jinja.package': 'yourapplication',81- 'jinja.package_path': 'res/templates',82- 'jinja.use_memcache': True83- })84-85-Note that it's a good idea to set the second parameter to an empty string.86-It's meant to be used as replacement for the turbogears package name but87-Jinja assumes that the name of the template does not include the package88-path.89-90-.. admonition:: Note91-92- 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`:95-96- .. sourcecode:: python97-98- return pylons.config.Config(tmpl_options, map, paths, strict_c=True)99-100-You can then render the template in the view like this:101-102-.. sourcecode:: python103-104- class ExampleController(BaseController):105-106- def index(self):107- c.title = "Your Page"108- c.message = 'hi'109- return render_response('jinja', 'test_template')110-111- def download(self):112- c.title = "Downloads"113- c.downloads = [1, 2, 3]114- return render_response('jinja', '/downloads.html')115-116-With the settings from above rendering the `index` action will result in117-rendering the template ``res/templates/test_template.html`` where res is118-a folder in the ``yourapplication`` python package.119-120-The `downloads` action uses the pylons specific leading foreslash notation.121-122-123-General Template Interface124-==========================125-126-Because nobody implemented this specification so far it's not documented here127-but in the sourcecode of the `plugin module`_. The specification itself is128-explained on the pocoo trac on the `General Template Interface`_ wiki page.129-130-131-Django132-======133-134-Using Jinja in django is straightforward because django has a pretty low135-level response interface. Just have a look at the `developer recipies`_,136-there are some examples for django. Starting with Jinja 1.2 there is also137-a contrib module that simplifies using Jinja in an unicode enabled django.138-139-Quickstart140-----------141-142-To get started execute the following code at the bottom of your settings.py143-or in some general application file such as urls.py or a central module. The144-only thing that matters is that it's executed right *after* the settings145-were set up and *before* `django.contrib.jinja` is imported::146-147- from jinja.contrib import djangosupport148- djangosupport.configure()149-150-What this does is setting up a Jinja environment for this django instance151-with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default152-django filters such as `date` and `timesince` which are not available in153-Jinja per default. If you want to change the list you can provide others154-by passing a list with filter import names as `convert_filters` keyword155-argument.156-157-All other keyword arguments are forwarded to the environment. If you want158-to provide a loader yourself pass it a loader keyword argument.159-160-Rendering Templates161--------------------162-163-To render a template you can use the functions `render_to_string` or164-`render_to_response` from the `django.contrib.jinja` module::165-166- from django.contrib.jinja import render_to_response167- resp = render_to_response('Hello {{ username }}!', {168- 'username': req.session['username']169- }, req)170-171-`render_to_string` and `render_to_response` take at least the name of172-the template as argument, then the optional dict which will become the173-context. If you also provide a request object as third argument the174-context processors will be applied.175-176-`render_to_response` also takes a forth parameter which can be the177-content type which defaults to `DEFAULT_CONTENT_TYPE`.178-179-Converting Filters180-------------------181-182-One of the useful objects provided by `django.contrib.jinja` is the183-`register` object which can be used to register filters, tests and184-global objects. You can also convert any filter django provides in185-a Jinja filter using `convert_django_filter`::186-187- from django.contrib.jinja import register, convert_django_filter188- from django.template.defaultfilters import floatformat189-190- register.filter(convert_django_filter(floatformat), 'floatformat')191-192-Available methods on the `register` object:193-194-``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.198-199-``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.204-205-``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.210-211-``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.214-215- 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.220-221- Example::222-223- def add_author(context, author=None):224- if author is not None:225- author = Author.objects.get(name=author)226- context['author'] = author227- return context228-229- register.context_inclusion(add_author, 'author_details.html',230- 'render_author_details')231-232- You can use it in the template like this then::233-234- {{ render_author_details('John Doe') }}235-236-``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.241-242-243-244-.. _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.txtdeleted:docs/src/fromdjango.txt-108 removed
1-===============================2-Differences To Django Templates3-===============================4-5-If you have previously worked with Django templates, you should find Jinja very6-familiar. In fact, most of the syntax elements look and work the same.7-8-However, Jinja provides some more syntax elements covered in the documentation9-and some work a bit different.10-11-Method Calls12-============13-14-In Django method calls work implicitly. With Jinja you have to specify that you15-want to call an object. Thus this Django code:16-17-.. sourcecode:: django18-19- {% for page in user.get_created_pages %}20- ...21- {% endfor %}22-23-will look like this in Jinja:24-25-.. sourcecode:: jinja26-27- {% for page in user.get_created_pages() %}28- ...29- {% endfor %}30-31-This allows you to pass variables to the function which is also used for32-macros and loop recursion, both features that don't exist in Django.33-34-Conditions35-==========36-37-In Django you can use the following constructs to check for equality:38-39-.. sourcecode:: django40-41- {% ifequals foo "bar" %}42- ...43- {% else %}44- ...45- {% endifequals %}46-47-In Jinja you can use the normal ``if`` statement in combination with48-operators:49-50-.. sourcecode:: jinja51-52- {% if foo == 'bar' %}53- ...54- {% else %}55- ...56- {% endif %}57-58-You can also have multiple ``elif`` branches in your template:59-60-.. sourcecode:: jinja61-62- {% if something %}63- ...64- {% elif otherthing %}65- ...66- {% elif foothing %}67- ...68- {% else %}69- ...70- {% endif %}71-72-Filter Arguments73-================74-75-Jinja provides more than one argument for filters. Also the syntax for argument76-passing is different. A template that looks like this in Django:77-78-.. sourcecode:: django79-80- {{ items|join:", " }}81-82-looks like this in jinja:83-84-.. sourcecode:: jinja85-86- {{ items|join(', ') }}87-88-In fact it's a bit more verbose but it allows different types of arguments - including89-variables - and more than one of them.90-91-Tests92-=====93-94-In addition to filters there also are tests you can perform using the `is` operator.95-Here are some examples:96-97-.. sourcecode:: jinja98-99- {% if user.user_id is odd %}100- {{ user.username|e }} is odd101- {% else %}102- hmm. {{ user.username|e }} looks pretty normal103- {% endif %}104-105-For a list of supported tests head over to the `syntax reference`_.106-107-108-.. _syntax reference: designerdoc.txtdeleted:docs/src/i18n.txt-113 removed
1-====================2-Internationalization3-====================4-5-Jinja includes support for internationalized templates. Because usually the6-application includes i18n/l10n code too there is no script to collect7-translatable strings and no default translation interface. A simple8-implementation wouldn't fit into every application so there are a few things9-you have to do.10-11-12-Writing A Translator13-====================14-15-The most important thing is writing a translator and subclassing the16-Environment so that Jinja knows about the translator. Then you have to17-think of how to resolve the current language. You probably use Jinja in a18-multithreaded environment where each thread (request) might want to have19-a different language. The best way is putting the current language into20-the context, this can work automatically if you create a helper function21-for template rendering. But that's up to you.22-23-However. For many web applications this might be a way:24-25-.. sourcecode:: python26-27- from jinja import Environment28- from myapplication import get_translator29-30- class ApplicationTranslator(object):31-32- def __init__(self, language):33- self.language = language34- self.translator = get_translator(language)35-36- def gettext(self, string):37- return self.translator.ugettext(string)38-39- def ngettext(self, singular, plural, n):40- return self.translator.ungettext(singuarl, plural, n)41-42-43- class ApplicationEnvironment(Environment):44-45- def get_translator(self, context):46- return ApplicationTranslator(context['LANGUAGE'])47-48-49- env = ApplicationEnvironment()50- tmpl = env.get_template('index.html')51- tmpl.render(LANGUAGE='de_DE')52-53-This example assumes that you use gettext and have a gettext `Translations`54-object which is returned by the `get_translator` function. But you don't55-have to use gettext. The only thing Jinja requires is an object with to56-functions/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 plural59-form for `count` items. Because some languages have no or multiple plural60-forms this is necessary.61-62-63-Translator Factory64-==================65-66-With Jinja 1.2 onwards it's possible to use a translator factory67-instead of an enviornment subclass to create a translator for a context.68-A translator factory is passed a context and has to return a translator.69-Because of the way classes work you can also assign a translator class70-that takes a context object as only argument as factory.71-72-Example:73-74-.. sourcecode:: python75-76- from jinja import Environment77- from myapplication import get_translator78-79- def translator_factory(context):80- return get_translator(context['LANGUAGE'])81-82- env = ApplicationEnvironment(translator_factory=translator_factory)83- tmpl = env.get_template('index.html')84- tmpl.render(LANGUAGE='de_DE')85-86-This example assumes that the translator returned by `get_translator`87-already has a gettext and ngettext function that returns unicode strings.88-89-90-Collecting Translations91-=======================92-93-The next step is to collect the translations. Every Jinja environment94-provides a function called `get_translations` which collects all95-translatable strings from an template.96-97-Example:98-99-.. sourcecode:: pycon100-101- >>> env.get_translations('index.html')102- [(1, u'foo', None), (2, u'Foo', None), (3, u'%(count)s Foo', u'%(count)s Foos')]103-104-The first item in the tuple is the linenumer, the second one is the105-singular form and the third is the plural form if given.106-107-Because Jinja is not bound to gettext you can now use these strings to108-create translation files for any translation system.109-110-*New in Jinja 1.1* You can now extract translations from strings according111-to the current envrionment settings too by using the environment method112-`get_translations_for_string` which takes a string containing a template113-as only argument. The return value is the same as for `get_translations`.deleted:docs/src/index.txt-74 removed
1-======================2-Documentation Overview3-======================4-5-Welcome in the Jinja documentation.6-7-- `Installing Jinja <installation.txt>`_8-9-- **Application Developer Documentation**:10-11- - `Quickstart <devintro.txt>`_ - getting started with Jinja12-13- - `Template Loaders <loaders.txt>`_ - documentation for the different14- loader types and how to write custom ones.15-16- - `Filter Functions <filters.txt>`_ - information about how to write17- custom filter functions.18-19- - `Test Functions <tests.txt>`_ - information about how to write20- custom test functions.21-22- - `Global Objects <objects.txt>`_ - information about the special global23- namespace in Jinja templates.24-25- - `Streaming Interface <streaming.txt>`_ - using Jinja for big templates26- by streaming the output.27-28- - `Internationalization <i18n.txt>`_ - how to internationalize applications29- using Jinja templates.30-31- - `Alternative Syntax <altsyntax.txt>`_ - changing the default Jinja32- block / variable / comment delimiters.33-34- - `API Documentation <api.txt>`_ - API documentation for public Jinja35- objects like `Environment`.36-37- - `Translators <translators.txt>`_ - explanation about the Jinja template38- translation interface.39-40- - `Framework Integration <frameworks.txt>`_ - integrating Jinja into41- python frameworks.42-43- - `Debugging Support <debugging.txt>`_ - debugging Jinja templates.44-45- - `Developer Recipies <devrecipies.txt>`_ - tips and tricks for application46- developers.47-48-- **Template Designer Documentation**:49-50- - `Syntax Reference <designerdoc.txt>`_ - quick overview over the Jinja51- syntax elements.52-53- - `Template Inheritance <inheritance.txt>`_ - template inheritance howto.54-55- - `Filters, Tests and Helper Functions <builtins.txt>`_ - list of filters56- and test/helper functions.57-58- - `Whitespace and Escaping <escaping.txt>`_ - how to escape markup and59- control whitespace.60-61- - `Scopes and Variable Behavior <scopes.txt>`_ - behavior of undefined62- variables and scoping rules.63-64- - `Template Internationalization <templatei18n.txt>`_ - how to internationalize65- Jinja templates.66-67- - `Differences To Django <fromdjango.txt>`_ - coming from django? Then this68- document is for you.69-70- - `Designer Recipies <recipies.txt>`_ - various tips and tricks for designers.71-72-- `Changelog <changelog.txt>`_73-74-There is also support via IRC on the ``#pocoo`` channel on `irc.freenode.net`.deleted:docs/src/inheritance.txt-186 removed
1-====================2-Template Inheritance3-====================4-5-The most powerful part of Jinja is template inheritance. Template inheritance6-allows you to build a base "skeleton" template that contains all the common7-elements of your site and defines **blocks** that child templates can override.8-9-Sounds complicated but is very basic. It's easiest to understand it by starting10-with an example.11-12-13-Base Template14-=============15-16-This template, which we'll call ``base.html``, defines a simple HTML skeleton17-document that you might use for a simple two-column page. It's the job of18-"child" templates to fill the empty blocks with content:19-20-.. sourcecode:: html+jinja21-22- <!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>34-35- <div id="footer">36- {% block footer %}37- © Copyright 2006 by <a href="http://mydomain.tld">myself</a>.38- {% endblock %}39- </div>40- </body>41-42-In this example, the ``{% block %}`` tags define four blocks that child templates43-can fill in. All the `block` tag does is to tell the template engine that a44-child template may override those portions of the template.45-46-47-Child Template48-==============49-50-A child template might look like this:51-52-.. sourcecode:: html+jinja53-54- {% extends "base.html" %}55- {% block title %}Index{% endblock %}56-57- {% 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 %}71-72-The ``{% extends %}`` tag is the key here. It tells the template engine that73-this template "extends" another template. When the template system evaluates74-this template, first it locates the parent. It must be always the first tag75-in a template but whitespace or a comment is allowed before. This was not76-enforced with Jinja 1.0 and 1.1, it does however raise a syntax error with77-1.2 or later.78-79-The filename of the template depends on the template loader. For example the80-``FileSystemLoader`` allows you to access other templates by giving the81-filename. You can access templates in subdirectories with an slash:82-83-.. sourcecode:: jinja84-85- {% extends "layout/default.html" %}86-87-But this behavior can depend on the application using Jinja.88-89-Note that since the child template didn't define the ``footer`` block, the90-value from the parent template is used instead.91-92-.. admonition:: Note93-94- 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.100-101-102-How Inheritance Works Internally103-================================104-105-Inheritance in Jinja is straightforward. If a template contains an106-``{% extends %}`` tag it's considered being a child template, otherwise it's107-a layout template. In a layout template you can place blocks basically108-everywhere. In a child template blocks can only be located either at the109-top level or inside another block.110-111-Data outside of a block in a child template is executed before the layout112-template is rendered, thus you can use it to propagate data to the whole113-inheritance chain. Having a block in an invalid position you will receive114-an syntax error. Here some examples:115-116-**impossible**:117-118- .. sourcecode:: jinja119-120- {% extends 'master.html' %}121- {% if some_condition %}122- {% block body %}123- ...124- {% endblock %}125- {% endif %}126-127- This can't work because template inheritance works at translation /128- compilation time not at template execution.129-130-**possible**:131-132- .. sourcecode:: jinja133-134- {% extends 'master.html' %}135- {% block body %}136- {% if some_condition %}137- {% block myblock %}138- ...139- {% endblock %}140- {% endif %}141- {% endblock %}142-143- 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.146-147-148-.. admonition:: Note149-150- Unlike Python Jinja does not support multiple inheritance. So you can151- only have one extends tag with only one constant string argument.152-153-154-Super Blocks155-============156-157-Starting with `Jinja 1.1` it's possible to render the contents of the parent158-block. By calling it you get the results of the parent block back. If you want159-to get the data of the parent you can give it an offset:160-161-.. sourcecode:: jinja162-163- {{ super() }}164- return the parent data165-166- {{ super(1) }}167- the same as above168-169- {{ super(2) }}170- return the data of the second parent block171-172-173-Block Shortcuts174-===============175-176-With Jinja 1.1 onwards it's possible to have a shortcut syntax for blocks177-with few content. The following constructs do the same:178-179-.. sourcecode:: jinja180-181- {% block title %}{{ page_title }}{% endblock %}182-183- {% block title page_title %}184-185-Note that as soon as you specify a second argument it's threated as186-short block and Jinja won't look for an closing tag.deleted:docs/src/installation.txt-89 removed
1-============2-Installation3-============4-5-Jinja requires at least Python 2.3 to work correctly.6-7-8-Installing a released version9-=============================10-11-As a Python egg (via easy_install)12-----------------------------------13-14-You can install the most recent Jinja version using `easy_install`_::15-16- sudo easy_install Jinja17-18-This will install a Jinja egg in your Python installation's site-packages19-directory.20-21-From the tarball release22--------------------------23-24-1. Download the most recent tarball from the `download page`_25-2. Unpack the tarball26-3. ``sudo python setup.py install``27-28-Note that the last command will automatically download and install29-`setuptools`_ if you don't already have it installed. This requires a working30-internet connection.31-32-This will install Jinja into your Python installation's site-packages directory.33-34-35-Installing the development version36-==================================37-38-If you want to play around with the code39-----------------------------------------40-41-1. Install `mercurial`_42-2. ``svn co http://dev.pocoo.org/hg/jinja-main jinja``43-3. ``cd jinja``44-4. ``ln -s jinja /usr/lib/python2.X/site-packages``45-46-As an alternative to steps 4 you can also do ``python setup.py develop``47-which will install the package via setuptools in development mode. This also48-has the advantage that the c extensions are compiled.49-50-If you just want the latest features and use them51--------------------------------------------------52-53-::54- 55- sudo easy_install Jinja==dev56-57-This will install a Jinja egg containing the latest Subversion trunk code58-in your Python installation's site-packages directory. Every time the command59-is run, the sources are updated from Subversion.60-61-62-Windows Installation Information63-================================64-65-On windows computers without Visual Studio 2003 Jinja is unable to compile the66-C extensions. This is usually not a problem because there is a fallback for67-native Python implementations of those C libraries. However under certain68-conditions the installation may fail with an error message. In that case try69-to disable the extensions by passing the following parameters to setup.py::70-71- python setup.py install --without-speedups --without-extended-debugger72-73-74-Documentation75-=============76-77-The egg builds include a documentation which is available in the ``docs`` folder78-of the egg. If you're running linux you will find the documentation here::79-80- file:///usr/lib/python2.X/site-packages/Jinja-Y.Z-py2.X.egg/docs/index.html81-82-where ``X``, ``Y`` and ``Z`` must be replaced by the python / jinja version83-number.84-85-86-.. _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-================2-Template Loaders3-================4-5-This part of the documentation explains how to use and write a template loader.6-7-Builtin Loaders8-===============9-10-This list contains the builtin loaders you can use without further11-modification:12-13-[[list_of_loaders]]14-15-Loader Baseclasses16-==================17-18-With Jinja 1.1 onwards all the loaders have (except of the uncached)19-baseclasses. You can use them to mix your own caching layer in. This technique20-is described below. The `BaseLoader` itself is also a loader baseclass but21-because it's the baseclass of all loaders it's covered in the "Developing22-Loaders" section.23-24-[[list_of_baseloaders]]25-26-Developing Loaders27-==================28-29-Template loaders are just normal Python classes that have to provide some30-functions used to load and translate templates. Because some of the tasks31-a loader has to do are redundant there are some classes that make loader32-development easier.33-34-Here the implementation of a simple loader based on the `BaseLoader` from35-`jinja.loaders`:36-37-.. sourcecode:: python38-39- import codecs40- from os.path import join41- from jinja.loaders import BaseLoader42- from jinja.exceptions import TemplateNotFound43-44- class SimpleLoader(BaseLoader):45- 46- def __init__(self, path):47- self.path = path48-49- 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()58-59-The functions `load` and `parse` which are a requirement for a loader are60-added automatically by the `BaseLoader`. Instead of the normal `BaseLoader`61-you can use one of the other base loaders that already come with a proper62-`get_source` method for further modification. Those loaders however are63-new in Jinja 1.1.64-65-CachedLoaderMixin66------------------67-68-Additionally to the `BaseLoader` there is a mixin class called69-`CachedLoaderMixin` that implements memory and disk caching of templates.70-Note 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:72-73-.. sourcecode:: python74-75- import codecs76- from os.path import join, getmtime, exists77- from jinja.loaders import BaseLoaderCachedLoaderMixin78- from jinja.exceptions import TemplateNotFound79-80- 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- )93-94- 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()103-104- def check_source_changed(self, environment, name):105- fn = join(self.path, name)106- if exists(fn):107- return getmtime(fn)108- return -1109-110-You don't have to provide the `check_source_changed` method. If it doesn't111-exist the option `auto_reload` won't have an effect. Also note that the112-`check_source_changed` method must not raise an exception if the template113-does not exist but return ``-1``. The return value ``-1`` is considered114-"always reload" whereas ``0`` means "do not reload". The default return115-value for not existing templates should be ``-1``.116-117-For the default base classes that come with Jinja 1.1 onwards there exist118-also concrete implementations that support caching. The implementation119-just mixes in the `CachedLoaderMixin`.120-121-MemcachedLoaderMixin122---------------------123-124-*New in Jinja 1.1*125-126-The `MemcachedLoaderMixin` class adds support for `memcached`_ caching.127-There is only one builtin loader that mixes it in: The128-`MemcachedFileSystemLoader`. If you need other loaders with this mixin129-you can easily subclass one of the existing base loaders. Here an example130-for the `FunctionLoader`:131-132-.. sourcecode:: python133-134- from jinja.loaders import FunctionLoader, MemcachedLoaderMixin135-136- class MemcachedFunctionLoader(MemcachedLoaderMixin, FunctionLoader):137-138- 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- )146-147-This mixin requires the `python-memcached`_ library.148-149-.. _memcached: http://www.danga.com/memcached/150-.. _python-memcached: http://www.tummy.com/Community/software/python-memcached/151-152-153-How Mixin Classes Work154-======================155-156-The idea of the cached loader mixins is that you override the `load`157-method of the other base class so that it's only called to get the data158-from the loader and put it into a cache and then bypass the original `load`.159-160-This works because mixin classes, as well as the loaders are so called "new161-style classes" with a MRO (method resolution order). So it's possible to162-access the parent without actually knowing the name of it.163-164-Here as small mixin class that stores everything after loading in a165-dict:166-167-.. sourcecode:: python168-169- class SimpleCacheMixin(object):170-171- def __init__(self):172- self.__cache = {}173-174- 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 tmpl181-182-You can then mix the class in like any other mixin class. Note that183-all non public attributes **must** be prefixed with two underscores to184-enable the name mangling. Otherwise the mixin class could break the185-internal structure of the loader.186-187-The ``super(SimpleCacheMixin, self)`` call returns an object that looks188-up all the attributes you request in all the parent classes. The189-`SimpleCacheMixin` just has the `object` parent which makes it a new190-style 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 resulting192-class. Here a full example.193-194-Combining Everything195-====================196-197-Here a full example with a custom cache mixin and a custom base loader:198-199-.. sourcecode:: python200-201- import codecs202- from os.path import join203- from jinja.loaders import BaseLoader204- from jinja.exceptions import TemplateNotFound205-206- class SimpleBaseLoader(BaseLoader):207- 208- def __init__(self, path):209- self.path = path210-211- 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()220-221-222- class SimpleCacheMixin(object):223-224- def __init__(self):225- self.__cache = {}226-227- 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 tmpl234-235-236- class SimpleLoader(SimpleBaseLoader, SimpleCacheMixin):237-238- def __init__(self, path):239- SimpleBaseLoader.__init__(self, path)240- SimpleCacheMixin.__init__()241-242-You can of course put all the functionallity into the `SimpleLoader` but then243-you cannot exchange parts of it without rewriting much code. In the example244-above replacing the `SimpleCacheMixin` with a `MemcachedLoaderMixin` is a245-matter of 20 seconds.deleted:docs/src/objects.txt-154 removed
1-==============2-Global objects3-==============4-5-This section covers the behavior of global objects in the Jinja namespace and6-also the behavior of their attributes.7-8-9-Functions10-=========11-12-`Filters`_ and `Tests`_ are special kind of functions you cannot call without13-and argument. Global functions are different. Those are really just ordinary14-python functions. You can register them on the global namespace easily:15-16-.. sourcecode:: python17-18- def my_function():19- return [1, 2, 3]20-21- env.globals['my_function'] = my_function22-23-In the template you can not call it like this:24-25-.. sourcecode:: jinja26-27- {{ my_function() }}28-29-Of couse you can pass any argument to it. But what if you want to access the30-context or environment? In that case you have to decorate a function or mark31-it (both work exactly the same, but the decorator way is probably nicer if you32-have python >= 2.4):33-34-.. sourcecode:: python35-36- from cgi import escape37- from pprint import pformat38- from jinja.datastructure import contextcallable39-40- @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)47-48-If this function is registered in the environment namespace then and called49-from the template it should return the content of the context as simple html50-template. Of course you can modify the context too. For more informations about51-the context object have a look at the `context object`_ documentation.52-53-The new ``{% call %}`` tag that exists with Jinja 1.1 onwards can not only54-be used with Jinja macros but also with Python functions. If a template55-designers uses the ``{% call %}`` tag to call a function provided by the56-application Jinja will call this function with a keyword argument called57-`caller` which points to a `function`. If you call this function (optionally58-with keyword arguments that appear in the context) you get a string back59-that was the content of that block. This should explain this:60-61-.. sourcecode:: python62-63- 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)68-69-This can be used like this in the template now:70-71-.. sourcecode:: html+jinja72-73- {% call make_dialog('Dialog Title') %}74- This is the body of the dialog entitled "{{ title }}".75- {% endcall %}76-77-Deferred Values78-===============79-80-You can pass functions to the template that are called to provide values at81-first access. Say you want to pass the list of recently written comments to82-all templates. But not necessarily every template will render that. In that83-situation 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:86-87-.. sourcecode:: python88-89- from jinja.datastructure import Deferred90- from yourapplication.models import Comments91-92- def get_recent_comments(env, context, name):93- # do what ever you want here.94- return Comments.get_recent(10)95-96- env.globals['recent_comments'] = Deferred(get_recent_comments)97-98-The function is always called with the same arguments. The first one is the99-current environment, the second the context and the third is the name of the100-variable. In this example ``recent_comments``.101-102-The value is cached until rendering/streaming finished.103-104-Unsafe Methods / Attributes105-===========================106-107-Because Jinja is sandboxed it provides several ways to prevent unsafe attribute108-access. You can mark both attributes and methods as unsafe:109-110-.. sourcecode:: python111-112- from jinja.datastructure import unsafe113-114- class MyModel(...):115-116- # 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']121-122- def __init__(self, ...):123- ...124- self.a = ...125- self.b = ...126-127- # python2.4 way of marking methods128- @unsafe129- def save(self):130- """Save the model."""131-132- # python2.3 way for the same133- def delete(self):134- """Delete the model."""135- delete.jinja_unsafe_call = True136-137-138-Bypassing Automatic Filtering139-=============================140-141-With Jinja 1.1 it's possible to assign filters to any variable printed. Of142-course there are ways to bypass that in order to make sure an object does143-not get escaped etc.144-145-In order to disable automatic filtering for an object you have to make146-sure that it's either an subclass of `unicode` or implements a147-`__unicode__` method. `__str__` will work too as long as the return value148-only contains ASCII values. Additionally you have to add an attribute to149-that object named `jinja_no_finalization` and set that to `True`.150-151-152-.. _Filters: filters.txt153-.. _Tests: tests.txt154-.. _context object: contextenv.txtdeleted:docs/src/recipies.txt-184 removed
1-========2-Recipies3-========4-5-Here are some typical recipes for the usage of Jinja templates.6-7-Alternating Rows8-================9-10-If you want to have different styles for each row of a table or11-list you can use the ``cycle`` tag:12-13-.. sourcecode:: html+jinja14-15- <ul>16- {% for row in sequence %}17- <li class="{% cycle 'even', 'odd' %}">{{ row|e }}</li>18- {% endfor %}19- </ul>20-21-``cycle`` can take an unlimited amount of strings. Each time this22-tag is encountered the next item from the list is rendered.23-If you pass it just one argument it's meant to be a sequence.24-25-26-Active Menu Item27-================28-29-Often you want to have a navigation bar with an active navigation30-item. This is really simple to achieve. Because ``set`` tags outside31-of ``blocks`` are global you can do something like this:32-33-**layout.html**:34-35- .. sourcecode:: html+jinja36-37- {% 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- ...50-51-**index.html**:52-53- .. sourcecode:: jinja54-55- {% extends "layout.html" %}56- {% set active_page = "index" %}57-58-59-Sitemap60-=======61-62-To create a sitemap you can either use the ``for`` tag or a ``macro``63-that calls itself. The datastructures should look like this:64-65-.. sourcecode:: python66-67- {'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- ]}112-113-Now you can create a sitemap using ``for``:114-115-.. sourcecode:: html+jinja116-117- <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>123-124-Or by using a ``macro`` that calls itself:125-126-.. sourcecode:: html+jinja127-128- {% 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>135-136-137-Using A Block Multiple Times138-============================139-140-Blocks have the small disadvantage that they work both ways which is a problem141-if you want to render a block two times on a page. Here a nice little142-workaround for this limitation:143-144-.. sourcecode:: html+jinja145-146- <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>156-157-Or if you use the `capture` filter in `clean` mode:158-159-.. sourcecode:: html+jinja160-161- {% 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>172-173-174-Vim Syntax Highlighting175-=======================176-177-Because of the similar syntax to django you can use the django highlighting178-plugin for jinja too. There is however a Jinja syntax highlighting plugin179-too which supports all of the syntax elements.180-181-You can download it from the vim webpage: `jinja.vim`_182-183-184-.. _jinja.vim: http://www.vim.org/scripts/script.php?script_id=1856deleted:docs/src/scopes.txt-186 removed
1-============================2-Scopes and Variable Behavior3-============================4-5-This section of the documentation covers the Jinja behavior regarding6-variable visibility.7-8-9-Scopes10-======11-12-Jinja has multiple scopes. A scope is something like a new transparent foil on13-a stack of foils. You can only write to the outermost foil but read all of them14-since you can look through them. If you remove the top foil all data on that15-foil disappears. Some tags in Jinja add a new layer to the stack. Currently16-these are `block`, `for`, `macro` and `filter`. This means that variables and17-other elements defined inside a macro, loop or some of the other tags listed18-above will be only available in that block. Here an example:19-20-.. sourcecode:: jinja21-22- {% macro angryhello name %}23- {% set angryname = name|upper %}24- Hello {{ name }}. Hello {{ name }}!25- HELLO {{ angryname }}!!!!!!11126- {% endmacro %}27-28-The variable ``angryname`` just exists inside the macro, not outside it.29-30-Defined macros appear on the context as variables. Because of this, they are31-affected by the scoping too. A macro defined inside of a macro is just available32-in those two macros (the macro itself and the macro it's defined in).33-34-35-Template Globals36-================37-38-A special threatment exists for template code outside of visible blocks in39-child templates. This code will be executed **before** the layout template40-code. Thus it can be used to propagate values back to the layout template or41-import macros from templates for rendering.42-43-Such code can output data but it won't appear in the final rendering. So no44-additional whitespace will pollute the template.45-46-Because this code is executed before the actual layout template code it's47-possible that the layout code overrides some of those variables. Usually48-this is not a problem because of different variable names but it can be49-a problem if you plan to specify default values.50-51-In that case you have to test if the variable is not defined before setting52-it:53-54-.. sourcecode:: jinja55-56- {% if not page_title %}57- {% set page_title = 'Default Page Title' %}58- {% endif %}59-60-You can of course also use the `|default` filter.61-62-.. admonition:: Explanation63-64- This template stored as `a.html`:65-66- .. sourcecode:: html+jinja67-68- <title>{{ title|default('Untitled') }}</title>69- <body>{% block body %}{% endblock %}70-71- ...and this child template stored as `b.html`:72-73- .. sourcecode:: html+jinja74-75- {% extends 'a.html' %}76- {% include 'macros.tmpl' %}77- {% set title = 'My Page' %}78- {% block body %}{{ wrap(42) }}{% endblock %}79-80- ...and this code in `macros.tmpl`:81-82- .. sourcecode:: html+jinja83-84- {% macro wrap(text) %}85- [{{ text }}]86- {% endmacro %}87-88- ..will translate to something with the same semantics as this (just89- that the value is not stored in a variable):90-91- .. sourcecode:: html+jinja92-93- {% 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>103-104-.. admonition:: Note105-106- 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.110-111-112-Undefined Variables113-===================114-115-If you have already worked with python you probably know about the fact that116-undefined variables raise an exception. This is different in Jinja. There is a117-special value called `undefined` that represents values that do not exist.118-119-Depending on the configuration it will behave different.120-121-In order to check if a value is defined you can use the `defined` test:122-123-.. sourcecode:: jinja124-125- {{ myvariable is not defined }}126- will return true if the variable does not exist.127-128-`SilentUndefined`:129-130- 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.134-135- In order to check if a value is defined you can use the `defined` test:136-137- There are also some additional rules regarding this special value. Any138- mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand139- as result:140-141- .. sourcecode:: jinja142-143- {{ undefined + "foo" }}144- returns "foo"145-146- {{ undefined - 42 }}147- returns 42. Note: not -42!148-149- In any expression `undefined` evaluates to `false`. It has no length, all150- attribute calls return undefined, calling too:151-152- .. sourcecode:: jinja153-154- {{ undefined.attribute().attribute_too[42] }}155- still returns `undefined`.156-157-`ComplainingUndefined`:158-159- 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.162-163- It raises exceptions as soon as you either render it or want to iterate164- over it or try to access attributes etc.165-166-167-Overriding Variables Of Outer Scopes168-====================================169-170-*New in Jinja 1.2*171-172-Normally you cannot override a variable from an outer scope, you can just hide173-it. There is however a way to override a variable from an outer scope using the174-`set` tag, postfixed with a bang (!):175-176-.. sourcecode:: jinja177-178- {% set last_item = none %}179- {% for item in seq %}180- {% set last_item = item! %}181- {% endfor %}182-183-After the iteration `last_item` will point to the item of the last iteration.184-185-If `last_item` was not defined in the outer scope it would be defined in the186-outermost scope.deleted:docs/src/streaming.txt-74 removed
1-===================2-Streaming Interface3-===================4-5-With Jinja 1.1 onwards it's possible to stream the template output. This is6-usually a bad idea because it's slower than `render()` but there are some7-situations where it's useful.8-9-If you for example generate a file with a couple of megabytes you may want10-to pass the stream to the WSGI interface in order to keep the amount of11-memory used low and deliver the output to the browser as fast as possible.12-13-The streaming interface is straightforward. Instead of using `render()` you14-can call `stream()` which does pretty much the same but doesn't return a15-string but a `TemplateStream`:16-17-.. sourcecode:: pycon18-19- >>> 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>'34-35-As you can see each iteration is threated as template event here. But also36-other tags trigger events. Basically every tag yields one event, the37-`print` tag too. The only exception is the variable substitution syntax which38-is inserted into the template text data.39-40-Because some protocols like `WSGI` flush after each iteration if passed as41-response iterable it's better to buffer some events internally. You can do42-this by enable buffering using `enable_buffering` and passing it the buffer43-size which must be greater than one:44-45-.. sourcecode:: pycon46-47- >>> 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>'52-53-This will buffer 3 events before yielding. Disabling buffering works using the54-`disable_buffering` method. You can enable and disable buffering on the fly also55-if you have already iterated over that stream. To check if you are in buffered56-or unbuffered mode you can use the `.buffered` property:57-58-.. sourcecode:: pycon59-60- >>> stream.buffered61- False62- >>> stream.enable_buffering(20)63- >>> stream.buffered64- True65- >>> stream.disable_buffering()66- >>> stream.buffered67- False68-69-.. admonition:: Note70-71- Jinja uses buffering internally for some constructs like macros. A macro72- call is yielded as one event, independently of the internal structure.73-74- The same applies to recursive for loops and `{% filter %}` tags.deleted:docs/src/templatei18n.txt-83 removed
1-=============================2-Template Internationalization3-=============================4-5-If the application is configured for i18n, you can define translatable blocks6-for translators using the `trans` tag or the special underscore function:7-8-.. sourcecode:: jinja9-10- {% trans %}11- this is a translatable block12- {% endtrans %}13-14- {% trans "This is a translatable string" %}15-16- {{ _("This is a translatable string") }}17-18-The latter one is useful if you want translatable arguments for filters etc.19-If you want to use the ``_()`` syntax in an expression and have variables in20-the string you can add a substituation marker (``%s``) and use the `|format`21-filter to fill the slot:22-23-.. sourcecode:: jinja24-25- {{ _('Hello %s!')|format(username) }}26-27-If you have more than one substitution variable consider using the28-``{% trans %}`` tags or the `|dformat` filter, the latter however is new29-in Jinja 1.1.30-31-If you want to have plural forms too, use the `pluralize` block:32-33-.. sourcecode:: jinja34-35- {% trans users=users %}36- One user found.37- {% pluralize %}38- {{ users }} users found.39- {% endtrans %}40-41- {% 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 %}46-47-If you have multiple arguments, the first one is assumed to be the indicator (the48-number that is used to determine the correct singular or plural form. If you49-don't have the indicator variable on position 1 you have to tell the `pluralize`50-tag the correct variable name.51-52-Inside translatable blocks you cannot use blocks or expressions (however you can53-still use the ``raw`` block which will work as expected). The variable54-print syntax (``{{ variablename }}``) is the only way to insert the variables55-defined in the ``trans`` header. Filters must be applied in the header.56-57-.. admonition:: note58-59- 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:63-64- .. sourcecode:: jinja65-66- {% if count != 1 %}67- {{ count }} users found.68- {% else %}69- one user found.70- {% endif %}71-72-*New in Jinja 1.1*: It's now possible to use the marker name as implicit73-default:74-75-.. sourcecode:: jinja76-77- instead of this version:78-79- {% trans username=username %}Hello {{ username }}!{% endtrans %}80-81- you can now write this:82-83- {% trans username %}Hello {{ username }}!{% endtrans %}deleted:docs/src/tests.txt-30 removed
1-==============2-Test Functions3-==============4-5-In addition to filters, Jinja also supports test functions. Test functions6-always return either ``True`` or ``False``. Inside the template they are available7-using the `is` operator.8-9-Jinja comes with some builtin tests listed in the `designer documentation`_.10-11-Writing Test Functions12-======================13-14-Test functions look exactly like filters mentioned in the `filter documentation`_:15-16-.. sourcecode:: python17-18- def is_even():19- def wrapped(env, context, value):20- return value % 2 == 021- return wrapped22-23-Now you have to register that test on an environment:24-25-.. sourcecode:: python26-27- env.tests['even'] = is_even28-29-.. _designer documentation: builtins.txt30-.. _filter documentation: filters.txtdeleted:docs/src/translators.txt-10 removed
1-===========2-Translators3-===========4-5-Jinja translates the template sourcecode into executable python code behind6-the secenes. This is done by the python translator which is currently the7-only shipped translator. Because the interface isn't stable it's also not8-recommended yet to write other translators. However for one of the next Jinja9-versions a JavaScript translator is planned which allows you to translate10-Jinja 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.13+14+import sys, os15+16+# 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'))20+21+# General configuration22+# ---------------------23+24+# 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 = []27+28+# Add any paths that contain templates here, relative to this directory.29+templates_path = ['_templates']30+31+# The suffix of source filenames.32+source_suffix = '.rst'33+34+# The master toctree document.35+master_doc = 'index'36+37+# General substitutions.38+project = 'Jinja2'39+copyright = '2008, Armin Ronacher'40+41+# The default replacements for |version| and |release|, also used in various42+# other places throughout the built documents.43+#44+# The short X.Y version.45+version = '2.0'46+# The full version, including alpha/beta/rc tags.47+release = '2.0'48+49+# 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.53+today_fmt = '%B %d, %Y'54+55+# List of documents that shouldn't be included in the build.56+#unused_docs = []57+58+# If true, '()' will be appended to :func: etc. cross-reference text.59+#add_function_parentheses = True60+61+# If true, the current module name will be prepended to all description62+# unit titles (such as .. function::).63+#add_module_names = True64+65+# If true, sectionauthor and moduleauthor directives will be shown in the66+# output. They are ignored by default.67+#show_authors = False68+69+# The name of the Pygments (syntax highlighting) style to use.70+pygments_style = 'sphinx'71+72+73+# Options for HTML output74+# -----------------------75+76+# 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.79+html_style = 'default.css'80+81+# The name for this set of Sphinx documents. If None, it defaults to82+# "<project> v<release> documentation".83+#html_title = None84+85+# 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".88+html_static_path = ['_static']89+90+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,91+# using the given strftime format.92+html_last_updated_fmt = '%b %d, %Y'93+94+# If true, SmartyPants will be used to convert quotes and dashes to95+# typographically correct entities.96+#html_use_smartypants = True97+98+# Custom sidebar templates, maps document names to template names.99+#html_sidebars = {}100+101+# Additional templates that should be rendered to pages, maps page names to102+# template names.103+#html_additional_pages = {}104+105+# If false, no module index is generated.106+#html_use_modindex = True107+108+# If true, the reST sources are included in the HTML build as _sources/<name>.109+#html_copy_source = True110+111+# If true, an OpenSearch description file will be output, and all pages will112+# contain a <link> tag referring to it.113+#html_use_opensearch = False114+115+# Output file base name for HTML help builder.116+htmlhelp_basename = 'Jinja2doc'117+118+119+# Options for LaTeX output120+# ------------------------121+122+# The paper size ('letter' or 'a4').123+#latex_paper_size = 'letter'124+125+# The font size ('10pt', '11pt' or '12pt').126+#latex_font_size = '10pt'127+128+# Grouping the document tree into LaTeX files. List of tuples129+# (source start file, target name, title, author, document class [howto/manual]).130+latex_documents = [131+ ('index', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', 'manual'),132+]133+134+# Additional stuff for the LaTeX preamble.135+#latex_preamble = ''136+137+# Documents to append as an appendix to all manuals.138+#latex_appendices = []139+140+# If false, no module index is generated.141+#latex_use_modindex = Truedeleted:docs/generate.py-325 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-"""4- Generate Jinja Documentation5- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~6-7- Generates a bunch of html files containing the documentation.8-9- :copyright: 2006-2007 by Armin Ronacher, Georg Brandl.10- :license: BSD, see LICENSE for more details.11-"""12-import os13-import sys14-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))15-import re16-import inspect17-from datetime import datetime18-from cgi import escape19-20-from docutils import nodes21-from docutils.parsers.rst import directives22-from docutils.core import publish_parts23-from docutils.writers import html4css124-25-from jinja import Environment26-27-from pygments import highlight28-from pygments.lexers import get_lexer_by_name29-from pygments.formatters import HtmlFormatter30-31-def generate_list_of_filters():32- from jinja.filters import FILTERS33- result = []34-35- 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))43-44- 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 = ''50-51- 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))56-57- return '\n'.join(result)58-59-def generate_list_of_tests():60- from jinja.tests import TESTS61- result = []62-63- 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))71-72- 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 = ''78-79- 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))84-85- return '\n'.join(result)86-87-def generate_list_of_loaders():88- from jinja import loaders as loader_module89-90- 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())95-96- 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)))101-102- return '\n\n'.join(result)103-104-def generate_list_of_baseloaders():105- from jinja import loaders as loader_module106-107- 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())119-120- 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)))125-126- return '\n\n'.join(result)127-128-def generate_environment_doc():129- from jinja.environment import Environment130- return '%s\n\n%s' % (131- inspect.getdoc(Environment),132- inspect.getdoc(Environment.__init__)133- )134-135-e = Environment()136-137-PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')138-139-LIST_OF_FILTERS = generate_list_of_filters()140-LIST_OF_TESTS = generate_list_of_tests()141-LIST_OF_LOADERS = generate_list_of_loaders()142-LIST_OF_BASELOADERS = generate_list_of_baseloaders()143-ENVIRONMENT_DOC = generate_environment_doc()144-CHANGELOG = file(os.path.join(os.path.dirname(__file__), os.pardir, 'CHANGES'))\145- .read().decode('utf-8')146-147-FULL_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 }} — 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-''')193-194-PREPROC_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-''')200-201-def 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")]210-pygments_directive.arguments = (1, 0, 1)211-pygments_directive.content = 1212-directives.register_directive('sourcecode', pygments_directive)213-214-215-def 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 Translator223-224-225-class DocumentationWriter(html4css1.Writer):226-227- def __init__(self, link_style):228- html4css1.Writer.__init__(self)229- self.translator_class = create_translator(link_style)230-231- 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_toc240-241- 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))257-258- self._generated_toc = [('#%s' % href, caption) for href, caption in toc]259- # no further processing260- return []261-262-263-def 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- }284-285-286-def 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()303-304-305-def 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()318-319-320-def main(dst='html/', preproc=False, *sources):321- run(os.path.realpath(dst), str(preproc).lower() == 'true', sources)322-323-324-if __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.4+5+Welcome to Jinja2's documentation!6+==================================7+8+Contents:9+10+.. toctree::11+ :maxdepth: 212+13+Indices and tables14+==================15+16+* :ref:`genindex`17+* :ref:`modindex`18+* :ref:`search`19+added:docs/Makefile+70 added
1+# Makefile for Sphinx documentation2+#3+4+# You can set these variables from the command line.5+SPHINXOPTS =6+SPHINXBUILD = sphinx-build7+PAPER =8+9+# Internal variables.10+PAPEROPT_a4 = -D latex_paper_size=a411+PAPEROPT_letter = -D latex_paper_size=letter12+ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .13+14+.PHONY: help clean html web pickle htmlhelp latex changes linkcheck15+16+help: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"24+25+clean:26+ -rm -rf _build/*27+28+html:29+ mkdir -p _build/html _build/doctrees30+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html31+ @echo32+ @echo "Build finished. The HTML pages are in _build/html."33+34+pickle: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."41+42+web: pickle43+44+htmlhelp: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."50+51+latex: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."58+59+changes:60+ mkdir -p _build/changes _build/doctrees61+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes62+ @echo63+ @echo "The overview file is in _build/changes."64+65+linkcheck: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."