first version of the jinja2 docs
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 d134231 · Browse files · 10 files·+642 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+642 added−3 removed
- other:+642 added−3 removed
Provenance
- Commit
3c8b7ad- Tree
f65e57c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d134231
10 files changed+642 added−3 removed
added:docs/_build/.ignore
added:docs/_static/.ignore
added:docs/_templates/.ignore
added:docs/api.rst+191 added
1+API2+===3+4+.. module:: jinja25+ :synopsis: public Jinja2 API6+7+This document describes the API to Jinja2 and not the template language. It8+will be most useful as reference to those implementing the template interface9+to the application and not those who are creating Jinja2 templates.10+11+Basics12+------13+14+Jinja2 uses a central object called the template :class:`Environment`.15+Instances of this class are used to store the configuration, global objects16+and are used to load templates from the file system or other locations.17+Even if you are creating templates from string by using the constructor of18+:class:`Template` class, an environment is created automatically for you.19+20+Most applications will create one :class:`Environment` object on application21+initialization and use that to load templates. In some cases it's however22+useful to have multiple environments side by side, if different configurations23+are in use.24+25+The simplest way to configure Jinja2 to load templates for your application26+looks roughly like this::27+28+ from jinja2 import Environment, PackageLoader29+ env = Environment(loader=PackageLoader('yourapplication', 'templates'))30+31+This will create a template environment with the default settings and a32+loader that looks up the templates in the `templates` folder inside the33+`yourapplication` python package. Different loaders are available34+and you can also write your own if you want to load templates from a35+database or other resources.36+37+To load a template from this environment you just have to call the38+:meth:`get_template` method which then returns the loaded :class:`Template`::39+40+ template = env.get_template('mytemplate.html')41+42+To render it with some variables, just call the :meth:`render` method::43+44+ print template.render(the='variables', go='here')45+46+47+High Level API48+--------------49+50+.. autoclass:: jinja2.environment.Environment51+ :members: from_string, get_template, join_path52+53+ .. attribute:: shared54+55+ If a template was created by using the :class:`Template` constructor56+ an environment is created automatically. These environments are57+ created as shared environments which means that multiple templates58+ may have the same anonymous environment. For all shared environments59+ this attribute is `True`, else `False`.60+61+ .. attribute:: sandboxed62+63+ If the environment is sandboxed this attribute is `True`. For the64+ sandbox mode have a look at the documentation for the65+ :class:`~jinja2.sandbox.SandboxedEnvironment`.66+67+ .. attribute:: filters68+69+ A dict of filters for this environment. As long as no template was70+ loaded it's safe to add new filters or remove old.71+72+ .. attribute:: tests73+74+ A dict of test funcitons for this environment. As long as no75+ template way loaded it's safe to modify this dict.76+77+ .. attribute:: globals78+79+ A dict of global variables. These variables are always available80+ in a template and (if the optimizer is enabled) may not be81+ override by templates. As long as no template was loaded it's safe82+ to modify this dict.83+84+85+.. autoclass:: jinja2.Template86+ :members: render, stream, generate, include87+88+89+.. autoclass:: jinja2.environment.TemplateStream90+ :members: disable_buffering, enable_buffering91+92+93+Undefined Types94+---------------95+96+These classes can be used as undefined types. The :class:`Environment`97+constructor takes an `undefined` parameter that can be one of those classes98+or a custom subclass of :class:`Undefined`. Whenever the template engine is99+unable to look up a name or access an attribute one of those objects is100+created and returned. Some operations on undefined values are then allowed,101+others fail.102+103+The closest to regular Python behavior is the `StrictUndefined` which104+disallows all operations beside testing if it's an undefined object.105+106+.. autoclass:: jinja2.runtime.Undefined107+108+.. autoclass:: jinja2.runtime.DebugUndefined109+110+.. autoclass:: jinja2.runtime.StrictUndefined111+112+113+Loaders114+-------115+116+Loaders are responsible for loading templates from a resource such as the117+file system and for keeping the compiled modules in memory. These work like118+Python's `sys.modules` which keeps the imported templates in memory. Unlike119+`sys.modules` however this cache is limited in size by default and templates120+are automatically reloaded. Each loader that extends :class:`BaseLoader`121+supports this caching and accepts two parameters to configure it:122+123+`cache_size`124+ The size of the cache. Per default this is ``50`` which means that if125+ more than 50 templates are loaded the loader will clean out the least126+ recently used template. If the cache size is set to ``0`` templates are127+ recompiled all the time, if the cache size is ``-1`` the cache will not128+ be cleaned.129+130+`auto_reload`131+ Some loaders load templates from locations where the template sources132+ may change (ie: file system or database). If `auto_reload` is set to133+ `True` (default) every time a template is requested the loader checks134+ if the source changed and if yes, it will reload the template. For135+ higher performance it's possible to disable that.136+137+.. autoclass:: jinja2.loaders.FileSystemLoader138+139+.. autoclass:: jinja2.loaders.PackageLoader140+141+.. autoclass:: jinja2.loaders.DictLoader142+143+.. autoclass:: jinja2.loaders.FunctionLoader144+145+.. autoclass:: jinja2.loaders.PrefixLoader146+147+.. autoclass:: jinja2.loaders.ChoiceLoader148+149+All loaders are subclasses of :class:`BaseLoader`. If you want to create your150+own loader, subclass :class:`BaseLoader` and override `get_source`.151+152+.. autoclass:: jinja2.loaders.BaseLoader153+ :members: get_source, load154+155+156+Utilities157+---------158+159+These helper functions and classes are useful if you add custom filters or160+functions to a Jinja2 environment.161+162+.. autofunction:: jinja2.filters.environmentfilter163+164+.. autofunction:: jinja2.filters.contextfilter165+166+.. autofunction:: jinja2.utils.environmentfunction167+168+.. autofunction:: jinja2.utils.contextfunction169+170+.. function:: escape(s)171+172+ Convert the characters &, <, >, and " in string s to HTML-safe sequences.173+ Use this if you need to display text that might contain such characters174+ in HTML. This function will not escaped objects that do have an HTML175+ representation such as already escaped data.176+177+.. autoclass:: jinja2.utils.Markup178+179+180+Exceptions181+----------182+183+.. autoclass:: jinja2.exceptions.TemplateError184+185+.. autoclass:: jinja2.exceptions.UndefinedError186+187+.. autoclass:: jinja2.exceptions.TemplateNotFound188+189+.. autoclass:: jinja2.exceptions.TemplateSyntaxError190+191+.. autoclass:: jinja2.exceptions.TemplateAssertionErrormodified:docs/conf.py+2 added-2 removed
14 unmodified lines15 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'))19+sys.path.append(os.path.dirname(os.path.abspath(__file__)))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 = ['sphinx.ext.autodoc']26+extensions = ['sphinx.ext.autodoc', 'jinjaext']27 28 # Add any paths that contain templates here, relative to this directory.29 templates_path = ['_templates']30 111 unmodified linesadded:docs/intro.rst+60 added
1+Introduction2+============3+4+This is the documentation for the Jinja2 general purpose templating language.5+Jinja2 is a library for Python 2.4 and onwards that is designed to be flexible,6+fast and secure.7+8+If you have any exposure to other text-based template languages, such as Smarty or9+Django, you should feel right at home with Jinja2. It's both designer and10+developer friendly by sticking to Python's principles and adding functionality11+useful for templating environments.12+13+The key-features are...14+15+- ... **configurable syntax**. If you are generating LaTeX or other formats16+ with Jinja you can change the delimiters to something that integrates better17+ into the LaTeX markup.18+19+- ... **fast**. While performance is not the primarily target of Jinja2 it's20+ surprisingly fast. The overhead compared to regular Python code was reduced21+ to the very minimum.22+23+- ... **easy to debug**. Jinja2 integrates directly into the python traceback24+ system which allows you to debug Jinja templates with regular python25+ debugging helpers.26+27+- ... **secure**. It's possible to evaluate untrusted template code if the28+ optional sandbox is enabled. This allows Jinja2 to be used as templating29+ language for applications where users may modify the template design.30+31+32+Prerequisites33+-------------34+35+Jinja2 needs at least **Python 2.4** to run. Additionally a working C-compiler36+that can create python extensions should be installed for the debugger. If no37+C-compiler is available the `ctypes`_ module should be installed.38+39+.. _ctypes: http://python.net/crew/theller/ctypes/40+41+42+Basic API Usage43+---------------44+45+This section gives you a brief introduction to the Python API for Jinja templates.46+47+The most basic way to create a template and render it is through48+:class:`Template`. This however is not the recommended way to work with it,49+but the easiest50+51+>>> from jinja2 import Template52+>>> template = Template('Hello {{ name }}!')53+>>> template.render(name='John Doe')54+u'Hello John Doe!'55+56+By creating an instance of :class:`Template` you get back a new template57+object that provides a method called :meth:`~Template.render` which when58+called with a dict or keyword arguments expands the template. The dict59+or keywords arguments passed to the template are the so-called "context"60+of the template.added:docs/jinjaext.py+66 added
1+# -*- coding: utf-8 -*-2+"""3+ Jinja Documentation Extensions4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Support for automatically documenting filters and tests.7+8+ :copyright: Copyright 2008 by Armin Ronacher.9+ :license: BSD.10+"""11+import inspect12+from docutils import nodes13+from docutils.statemachine import ViewList14+from sphinx.ext.autodoc import prepare_docstring15+16+17+def format_filter(name, aliases, func):18+ try:19+ argspec = inspect.getargspec(func)20+ except:21+ try:22+ argspec = inspect.getargspec(func.__init__)23+ except:24+ try:25+ argspec = inspect.getargspec(func.__new__)26+ except:27+ return []28+ del argspec[0][0]29+ if getattr(func, 'environmentfilter', False) or \30+ getattr(func, 'contextfilter', False):31+ del argspec[0][0]32+ signature = inspect.formatargspec(*argspec)33+ result = ['.. function:: %s%s' % (name, signature), '']34+ for line in inspect.getdoc(func).splitlines():35+ result.append(' ' + line)36+ if aliases:37+ result.extend(('', ' :aliases: %s' % ', '.join(38+ '``%s``' % x for x in sorted(aliases))))39+ return result40+41+42+def jinja_filters(dirname, arguments, options, content, lineno,43+ content_offset, block_text, state, state_machine):44+ from jinja2.defaults import DEFAULT_FILTERS45+ mapping = {}46+ for name, func in DEFAULT_FILTERS.iteritems():47+ mapping.setdefault(func, []).append(name)48+ filters = []49+ for func, names in mapping.iteritems():50+ aliases = sorted(names, key=lambda x: len(x))51+ name = aliases.pop()52+ filters.append((name, aliases, func))53+ filters.sort()54+55+ result = ViewList()56+ for name, aliases, func in filters:57+ for item in format_filter(name, aliases, func):58+ result.append(item, '<jinjaext>')59+60+ node = nodes.paragraph()61+ state.nested_parse(result, content_offset, node)62+ return node.children63+64+65+def setup(app):66+ app.add_directive('jinjafilters', jinja_filters, 1, (0, 0, 0))added:docs/templates.rst+315 added
1+Template Designer Documentation2+===============================3+4+This document describes the syntax and semantics of the template engine and5+will be most useful as reference to those creating Jinja templates. As the6+template engine is very flexible the configuration from the application might7+be slightly different from here in terms of delimiters and behavior of8+undefined values.9+10+11+Synopsis12+--------13+14+A template is simply a text file. It can generate any text-based format15+(HTML, XML, CSV, LaTeX, etc.). It doesn't have a specific extension,16+``.html`` or ``.xml`` are just fine.17+18+A template contains **variables** or **expressions**, which get replaced with19+values when the template is evaluated, and tags, which control the logic of20+the template. The template syntax is heavily inspired by Django and Python.21+22+Below is a minimal template that illustrates a few basics. We will cover23+the details later in that document:24+25+.. sourcecode:: html+jinja26+27+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">28+ <html lang="en">29+ <head>30+ <title>My Webpage</title>31+ </head>32+ <body>33+ <ul id="navigation">34+ {% for item in navigation %}35+ <li><a href="{{ item.href }}">{{ item.caption }}</a></li>36+ {% endfor %}37+ </ul>38+39+ <h1>My Webpage</h1>40+ {{ a_variable }}41+ </body>42+ </html>43+44+This covers the default settings. The application developer might have45+changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.46+47+There are two kinds of delimiers. ``{% ... %}`` and ``{{ ... }}``. The first48+one is used to execute statements such as for-loops or assign values, the49+latter prints the result of the expression to the template.50+51+52+Variables53+---------54+55+The application passes variables to the templates you can mess around in the56+template. Variables may have attributes or elements on them you can access57+too. How a variable looks like, heavily depends on the application providing58+those.59+60+You can use a dot (``.``) to access attributes of a variable, alternative the61+so-called "subscribe" syntax (``[]``) can be used. The following lines do62+the same:63+64+.. sourcecode:: jinja65+66+ {{ foo.bar }}67+ {{ foo['bar'] }}68+69+It's important to know that the curly braces are *not* part of the variable70+but the print statement. If you access variables inside tags don't put the71+braces around.72+73+If a variable or attribute does not exist you will get back an undefined74+value. What you can do with that kind of value depends on the application75+configuration, the default behavior is that it evaluates to an empty string76+if printed and that you can iterate over it, but every other operation fails.77+78+79+Filters80+-------81+82+Variables can by modified by **filters**. Filters are separated from the83+variable by a pipe symbol (``|``) and may have optional arguments in84+parentheses. Multiple filters can be chained. The output of one filter is85+applied to the next.86+87+``{{ name|striptags|title }}`` for example will remove all HTML Tags from the88+`name` and title-cases it. Filters that accept arguments have parentheses89+around the arguments, like a function call. This example will join a list90+by spaces: ``{{ list|join(', ') }}``.91+92+The `builtin-filters`_ below describes all the builtin filters.93+94+95+Tests96+-----97+98+Beside filters there are also so called "tests" available. Tests can be used99+to test a variable against a common expression. To test a variable or100+expression you add `is` plus the name of the test after the variable. For101+example to find out if a variable is defined you can do ``name is defined``102+which will then return true or false depening on if `name` is defined.103+104+Tests can accept arguments too. If the test only takes one argument you can105+leave out the parentheses to group them. For example the following two106+expressions do the same:107+108+.. sourcecode:: jinja109+110+ {% if loop.index is divisibleby 3 %}111+ {% if loop.index is divisibleby(3) %}112+113+The `builtin-tests`_ below descibes all the builtin tests.114+115+116+Comments117+--------118+119+To comment-out part of a line in a template, use the comment syntax which is120+by default set to ``{# ... #}``. This is useful to comment out parts of the121+template for debugging or to add information for other template designers or122+yourself:123+124+.. sourcecode:: jinja125+126+ {# note: disabled template because we no longer user this127+ {% for user in users %}128+ ...129+ {% endfor %}130+ #}131+132+133+Template Inheritance134+--------------------135+136+The most powerful part of Jinja is template inheritance. Template inheritance137+allows you to build a base "skeleton" template that contains all the common138+elements of your site and defines **blocks** that child templates can override.139+140+Sounds complicated but is very basic. It's easiest to understand it by starting141+with an example.142+143+144+Base Template145+~~~~~~~~~~~~~146+147+This template, which we'll call ``base.html``, defines a simple HTML skeleton148+document that you might use for a simple two-column page. It's the job of149+"child" templates to fill the empty blocks with content:150+151+.. sourcecode:: html+jinja152+153+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">154+ <html lang="en">155+ <html xmlns="http://www.w3.org/1999/xhtml">156+ <head>157+ {% block head %}158+ <link rel="stylesheet" href="style.css" />159+ <title>{% block title %}{% endblock %} - My Webpage</title>160+ {% endblock %}161+ </head>162+ <body>163+ <div id="content">{% block content %}{% endblock %}</div>164+ <div id="footer">165+ {% block footer %}166+ © Copyright 2008 by <a href="http://domain.invalid/">you</a>.167+ {% endblock %}168+ </div>169+ </body>170+171+In this example, the ``{% block %}`` tags define four blocks that child templates172+can fill in. All the `block` tag does is to tell the template engine that a173+child template may override those portions of the template.174+175+Child Template176+~~~~~~~~~~~~~~177+178+A child template might look like this:179+180+.. sourcecode:: html+jinja181+182+ {% extends "base.html" %}183+ {% block title %}Index{% endblock %}184+ {% block head %}185+ {{ super() }}186+ <style type="text/css">187+ .important { color: #336699; }188+ </style>189+ {% endblock %}190+ {% block content %}191+ <h1>Index</h1>192+ <p class="important">193+ Welcome on my awsome homepage.194+ </p>195+ {% endblock %}196+197+The ``{% extends %}`` tag is the key here. It tells the template engine that198+this template "extends" another template. When the template system evaluates199+this template, first it locates the parent. The extends tag should be the200+first tag in the template. Everything before it is printed out normally and201+may cause confusion.202+203+The filename of the template depends on the template loader. For example the204+:class:`FileSystemLoader` allows you to access other templates by giving the205+filename. You can access templates in subdirectories with an slash:206+207+.. sourcecode:: jinja208+209+ {% extends "layout/default.html" %}210+211+But this behavior can depend on the application embedding Jinja. Note that212+since the child template doesn't define the ``footer`` block, the value from213+the parent template is used instead.214+215+You can't define multiple ``{% block %}`` tags with the same name in the216+same template. This limitation exists because a block tag works in "both"217+directions. That is, a block tag doesn't just provide a hole to fill - it218+also defines the content that fills the hole in the *parent*. If there219+were two similarly-named ``{% block %}`` tags in a template, that template's220+parent wouldn't know which one of the blocks' content to use.221+222+If you want to print a block multiple times you can however use the special223+`self` variable and call the block with that name:224+225+.. sourcecode:: jinja226+227+ <title>{% block title %}{% endblock %}</title>228+ <h1>{{ self.title() }}</h1>229+ {% block body %}{% endblock %}230+231+232+Unlike Python Jinja does not support multiple inheritance. So you can only have233+one extends tag called per rendering.234+235+236+Super Blocks237+~~~~~~~~~~~~238+239+It's possible to render the contents of the parent block by calling `super`.240+This gives back the results of the parent block:241+242+.. sourcecode:: jinja243+244+ {% block sidebar %}245+ <h3>Table Of Contents</h3>246+ ...247+ {{ super() }}248+ {% endblock %}249+250+251+HTML Escaping252+-------------253+254+When generating HTML from templates, there's always a risk that a variable will255+include characters that affect the resulting HTML. There are two approaches:256+manually escaping each variable or automatically escaping everything by default.257+258+Jinja supports both, but what is used depends on the application configuration.259+The default configuaration is no automatic escaping for various reasons:260+261+- escaping everything except of safe values will also mean that Jinja is262+ escaping variables known to not include HTML such as numbers which is263+ a huge performance hit.264+265+- The information about the safety of a variable is very fragile. It could266+ happen that by coercing safe and unsafe values the return value is double267+ escaped HTML.268+269+Working with Manual Escaping270+----------------------------271+272+If manual escaping is enabled it's **your** responsibility to escape273+variables if needed. What to escape? If you have a variable that *may*274+include any of the following chars (``>``, ``<``, ``&``, or ``"``) you275+**have to** escape it unless the variable contains well-formed and trusted276+HTML. Escaping works by piping the variable through the ``|e`` filter:277+``{{ user.username|e }}``.278+279+Working with Automatic Escaping280+-------------------------------281+282+When automatic escaping is enabled everything is escaped by default except283+for values explicitly marked as safe. Those can either be marked by the284+application or in the template by using the `|safe` filter. The main285+problem with this approach is that python itself doesn't have the concept286+of tainted values so the information if a value is safe or unsafe can get287+lost. If the information is lost escaping will take place which means that288+you could end up with double escaped contents.289+290+Double escaping is easy to avoid however, just relay on the tools Jinja2291+provides and don't use builtin python constructs such as the string modulo292+operator.293+294+Functions returning template data (macros, `super`, `self.BLOCKNAME`) return295+safe markup always.296+297+String literals in templates with automatic escaping are considered unsafe298+too. The reason for this is that the safe string is an extension to python299+and not every library will work properly with it.300+301+302+.. _builtin-filters:303+304+List of Builtin Filters305+-----------------------306+307+.. jinjafilters::308+309+310+.. _builtin-tests:311+312+List of Builtin Tests313+---------------------314+315+blehmodified:jinja2/filters.py+1 added
605 unmodified lines606 'forceescape': do_forceescape,607 'capitalize': do_capitalize,608 'title': do_title,609 'default': do_default,610+ 'd': do_default,611 'join': do_join,612 'count': len,613 'dictsort': do_dictsort,614 'length': len,31 unmodified linesmodified:jinja2/tests.py+7 added-1 removed
110 unmodified lines111 return False112 return True113 114 115+def test_escaped(value):116+ """Check if the value is escaped."""117+ return hasattr(value, '__html__')118+119+120 TESTS = {121 'odd': test_odd,122 'even': test_even,123 'divisibleby': test_divisibleby,6 unmodified lines130 'number': test_number,131 'sequence': test_sequence,132 'iterable': test_iterable,133 'callable': callable,129- 'sameas': test_sameas134+ 'sameas': test_sameas,135+ 'escaped': test_escaped136 }