Skip to content
Myr

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

10 files+642 added−3 removed

added:docs/_build/.ignore
added:docs/_static/.ignore
added:docs/_templates/.ignore
added:docs/api.rst+191 added
1API2===34.. module:: jinja25 :synopsis: public Jinja2 API67This document describes the API to Jinja2 and not the template language. It8will be most useful as reference to those implementing the template interface9to the application and not those who are creating Jinja2 templates.1011Basics12------1314Jinja2 uses a central object called the template :class:`Environment`.15Instances of this class are used to store the configuration, global objects16and are used to load templates from the file system or other locations.17Even if you are creating templates from string by using the constructor of18:class:`Template` class, an environment is created automatically for you.1920Most applications will create one :class:`Environment` object on application21initialization and use that to load templates. In some cases it's however22useful to have multiple environments side by side, if different configurations23are in use.2425The simplest way to configure Jinja2 to load templates for your application26looks roughly like this::2728 from jinja2 import Environment, PackageLoader29 env = Environment(loader=PackageLoader('yourapplication', 'templates'))3031This will create a template environment with the default settings and a32loader that looks up the templates in the `templates` folder inside the33`yourapplication` python package. Different loaders are available34and you can also write your own if you want to load templates from a35database or other resources.3637To load a template from this environment you just have to call the38:meth:`get_template` method which then returns the loaded :class:`Template`::3940 template = env.get_template('mytemplate.html')4142To render it with some variables, just call the :meth:`render` method::4344 print template.render(the='variables', go='here')454647High Level API48--------------4950.. autoclass:: jinja2.environment.Environment51 :members: from_string, get_template, join_path5253 .. attribute:: shared5455 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`.6061 .. attribute:: sandboxed6263 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`.6667 .. attribute:: filters6869 A dict of filters for this environment. As long as no template was70 loaded it's safe to add new filters or remove old.7172 .. attribute:: tests7374 A dict of test funcitons for this environment. As long as no75 template way loaded it's safe to modify this dict.7677 .. attribute:: globals7879 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.838485.. autoclass:: jinja2.Template86 :members: render, stream, generate, include878889.. autoclass:: jinja2.environment.TemplateStream90 :members: disable_buffering, enable_buffering919293Undefined Types94---------------9596These classes can be used as undefined types. The :class:`Environment`97constructor takes an `undefined` parameter that can be one of those classes98or a custom subclass of :class:`Undefined`. Whenever the template engine is99unable to look up a name or access an attribute one of those objects is100created and returned. Some operations on undefined values are then allowed,101others fail.102103The closest to regular Python behavior is the `StrictUndefined` which104disallows all operations beside testing if it's an undefined object.105106.. autoclass:: jinja2.runtime.Undefined107108.. autoclass:: jinja2.runtime.DebugUndefined109110.. autoclass:: jinja2.runtime.StrictUndefined111112113Loaders114-------115116Loaders are responsible for loading templates from a resource such as the117file system and for keeping the compiled modules in memory. These work like118Python's `sys.modules` which keeps the imported templates in memory. Unlike119`sys.modules` however this cache is limited in size by default and templates120are automatically reloaded. Each loader that extends :class:`BaseLoader`121supports this caching and accepts two parameters to configure it:122123`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.129130`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.136137.. autoclass:: jinja2.loaders.FileSystemLoader138139.. autoclass:: jinja2.loaders.PackageLoader140141.. autoclass:: jinja2.loaders.DictLoader142143.. autoclass:: jinja2.loaders.FunctionLoader144145.. autoclass:: jinja2.loaders.PrefixLoader146147.. autoclass:: jinja2.loaders.ChoiceLoader148149All loaders are subclasses of :class:`BaseLoader`. If you want to create your150own loader, subclass :class:`BaseLoader` and override `get_source`.151152.. autoclass:: jinja2.loaders.BaseLoader153 :members: get_source, load154155156Utilities157---------158159These helper functions and classes are useful if you add custom filters or160functions to a Jinja2 environment.161162.. autofunction:: jinja2.filters.environmentfilter163164.. autofunction:: jinja2.filters.contextfilter165166.. autofunction:: jinja2.utils.environmentfunction167168.. autofunction:: jinja2.utils.contextfunction169170.. function:: escape(s)171172 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.176177.. autoclass:: jinja2.utils.Markup178179180Exceptions181----------182183.. autoclass:: jinja2.exceptions.TemplateError184185.. autoclass:: jinja2.exceptions.UndefinedError186187.. autoclass:: jinja2.exceptions.TemplateNotFound188189.. autoclass:: jinja2.exceptions.TemplateSyntaxError190191.. autoclass:: jinja2.exceptions.TemplateAssertionError
modified:docs/conf.py+2 added-2 removed
14 unmodified lines
1516# 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'))19sys.path.append(os.path.dirname(os.path.abspath(__file__)))2021# General configuration22# ---------------------2324# Add any Sphinx extension module names here, as strings. They can be extensions25# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.26extensions = ['sphinx.ext.autodoc']26extensions = ['sphinx.ext.autodoc', 'jinjaext']2728# Add any paths that contain templates here, relative to this directory.29templates_path = ['_templates']30
111 unmodified lines
added:docs/intro.rst+60 added
1Introduction2============34This is the documentation for the Jinja2 general purpose templating language.5Jinja2 is a library for Python 2.4 and onwards that is designed to be flexible,6fast and secure.78If you have any exposure to other text-based template languages, such as Smarty or9Django, you should feel right at home with Jinja2. It's both designer and10developer friendly by sticking to Python's principles and adding functionality11useful for templating environments.1213The key-features are...1415- ... **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.1819- ... **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.2223- ... **easy to debug**. Jinja2 integrates directly into the python traceback24 system which allows you to debug Jinja templates with regular python25 debugging helpers.2627- ... **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.303132Prerequisites33-------------3435Jinja2 needs at least **Python 2.4** to run. Additionally a working C-compiler36that can create python extensions should be installed for the debugger. If no37C-compiler is available the `ctypes`_ module should be installed.3839.. _ctypes: http://python.net/crew/theller/ctypes/404142Basic API Usage43---------------4445This section gives you a brief introduction to the Python API for Jinja templates.4647The 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,49but the easiest5051>>> from jinja2 import Template52>>> template = Template('Hello {{ name }}!')53>>> template.render(name='John Doe')54u'Hello John Doe!'5556By creating an instance of :class:`Template` you get back a new template57object that provides a method called :meth:`~Template.render` which when58called with a dict or keyword arguments expands the template. The dict59or keywords arguments passed to the template are the so-called "context"60of the template.
added:docs/jinjaext.py+66 added
1# -*- coding: utf-8 -*-2"""3 Jinja Documentation Extensions4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Support for automatically documenting filters and tests.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import inspect12from docutils import nodes13from docutils.statemachine import ViewList14from sphinx.ext.autodoc import prepare_docstring151617def 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 result404142def 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()5455 result = ViewList()56 for name, aliases, func in filters:57 for item in format_filter(name, aliases, func):58 result.append(item, '<jinjaext>')5960 node = nodes.paragraph()61 state.nested_parse(result, content_offset, node)62 return node.children636465def setup(app):66 app.add_directive('jinjafilters', jinja_filters, 1, (0, 0, 0))
added:docs/templates.rst+315 added
1Template Designer Documentation2===============================34This document describes the syntax and semantics of the template engine and5will be most useful as reference to those creating Jinja templates. As the6template engine is very flexible the configuration from the application might7be slightly different from here in terms of delimiters and behavior of8undefined values.91011Synopsis12--------1314A 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.1718A template contains **variables** or **expressions**, which get replaced with19values when the template is evaluated, and tags, which control the logic of20the template. The template syntax is heavily inspired by Django and Python.2122Below is a minimal template that illustrates a few basics. We will cover23the details later in that document:2425.. sourcecode:: html+jinja2627 <!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>3839 <h1>My Webpage</h1>40 {{ a_variable }}41 </body>42 </html>4344This covers the default settings. The application developer might have45changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.4647There are two kinds of delimiers. ``{% ... %}`` and ``{{ ... }}``. The first48one is used to execute statements such as for-loops or assign values, the49latter prints the result of the expression to the template.505152Variables53---------5455The application passes variables to the templates you can mess around in the56template. Variables may have attributes or elements on them you can access57too. How a variable looks like, heavily depends on the application providing58those.5960You can use a dot (``.``) to access attributes of a variable, alternative the61so-called "subscribe" syntax (``[]``) can be used. The following lines do62the same:6364.. sourcecode:: jinja6566 {{ foo.bar }}67 {{ foo['bar'] }}6869It's important to know that the curly braces are *not* part of the variable70but the print statement. If you access variables inside tags don't put the71braces around.7273If a variable or attribute does not exist you will get back an undefined74value. What you can do with that kind of value depends on the application75configuration, the default behavior is that it evaluates to an empty string76if printed and that you can iterate over it, but every other operation fails.777879Filters80-------8182Variables can by modified by **filters**. Filters are separated from the83variable by a pipe symbol (``|``) and may have optional arguments in84parentheses. Multiple filters can be chained. The output of one filter is85applied to the next.8687``{{ name|striptags|title }}`` for example will remove all HTML Tags from the88`name` and title-cases it. Filters that accept arguments have parentheses89around the arguments, like a function call. This example will join a list90by spaces: ``{{ list|join(', ') }}``.9192The `builtin-filters`_ below describes all the builtin filters.939495Tests96-----9798Beside filters there are also so called "tests" available. Tests can be used99to test a variable against a common expression. To test a variable or100expression you add `is` plus the name of the test after the variable. For101example to find out if a variable is defined you can do ``name is defined``102which will then return true or false depening on if `name` is defined.103104Tests can accept arguments too. If the test only takes one argument you can105leave out the parentheses to group them. For example the following two106expressions do the same:107108.. sourcecode:: jinja109110 {% if loop.index is divisibleby 3 %}111 {% if loop.index is divisibleby(3) %}112113The `builtin-tests`_ below descibes all the builtin tests.114115116Comments117--------118119To comment-out part of a line in a template, use the comment syntax which is120by default set to ``{# ... #}``. This is useful to comment out parts of the121template for debugging or to add information for other template designers or122yourself:123124.. sourcecode:: jinja125126 {# note: disabled template because we no longer user this127 {% for user in users %}128 ...129 {% endfor %}130 #}131132133Template Inheritance134--------------------135136The most powerful part of Jinja is template inheritance. Template inheritance137allows you to build a base "skeleton" template that contains all the common138elements of your site and defines **blocks** that child templates can override.139140Sounds complicated but is very basic. It's easiest to understand it by starting141with an example.142143144Base Template145~~~~~~~~~~~~~146147This template, which we'll call ``base.html``, defines a simple HTML skeleton148document that you might use for a simple two-column page. It's the job of149"child" templates to fill the empty blocks with content:150151.. sourcecode:: html+jinja152153 <!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 &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.167 {% endblock %}168 </div>169 </body>170171In this example, the ``{% block %}`` tags define four blocks that child templates172can fill in. All the `block` tag does is to tell the template engine that a173child template may override those portions of the template.174175Child Template176~~~~~~~~~~~~~~177178A child template might look like this:179180.. sourcecode:: html+jinja181182 {% 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 %}196197The ``{% extends %}`` tag is the key here. It tells the template engine that198this template "extends" another template. When the template system evaluates199this template, first it locates the parent. The extends tag should be the200first tag in the template. Everything before it is printed out normally and201may cause confusion.202203The filename of the template depends on the template loader. For example the204:class:`FileSystemLoader` allows you to access other templates by giving the205filename. You can access templates in subdirectories with an slash:206207.. sourcecode:: jinja208209 {% extends "layout/default.html" %}210211But this behavior can depend on the application embedding Jinja. Note that212since the child template doesn't define the ``footer`` block, the value from213the parent template is used instead.214215You can't define multiple ``{% block %}`` tags with the same name in the216same template. This limitation exists because a block tag works in "both"217directions. That is, a block tag doesn't just provide a hole to fill - it218also defines the content that fills the hole in the *parent*. If there219were two similarly-named ``{% block %}`` tags in a template, that template's220parent wouldn't know which one of the blocks' content to use.221222If you want to print a block multiple times you can however use the special223`self` variable and call the block with that name:224225.. sourcecode:: jinja226227 <title>{% block title %}{% endblock %}</title>228 <h1>{{ self.title() }}</h1>229 {% block body %}{% endblock %}230231232Unlike Python Jinja does not support multiple inheritance. So you can only have233one extends tag called per rendering.234235236Super Blocks237~~~~~~~~~~~~238239It's possible to render the contents of the parent block by calling `super`.240This gives back the results of the parent block:241242.. sourcecode:: jinja243244 {% block sidebar %}245 <h3>Table Of Contents</h3>246 ...247 {{ super() }}248 {% endblock %}249250251HTML Escaping252-------------253254When generating HTML from templates, there's always a risk that a variable will255include characters that affect the resulting HTML. There are two approaches:256manually escaping each variable or automatically escaping everything by default.257258Jinja supports both, but what is used depends on the application configuration.259The default configuaration is no automatic escaping for various reasons:260261- 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.264265- 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.268269Working with Manual Escaping270----------------------------271272If manual escaping is enabled it's **your** responsibility to escape273variables if needed. What to escape? If you have a variable that *may*274include any of the following chars (``>``, ``<``, ``&``, or ``"``) you275**have to** escape it unless the variable contains well-formed and trusted276HTML. Escaping works by piping the variable through the ``|e`` filter:277``{{ user.username|e }}``.278279Working with Automatic Escaping280-------------------------------281282When automatic escaping is enabled everything is escaped by default except283for values explicitly marked as safe. Those can either be marked by the284application or in the template by using the `|safe` filter. The main285problem with this approach is that python itself doesn't have the concept286of tainted values so the information if a value is safe or unsafe can get287lost. If the information is lost escaping will take place which means that288you could end up with double escaped contents.289290Double escaping is easy to avoid however, just relay on the tools Jinja2291provides and don't use builtin python constructs such as the string modulo292operator.293294Functions returning template data (macros, `super`, `self.BLOCKNAME`) return295safe markup always.296297String literals in templates with automatic escaping are considered unsafe298too. The reason for this is that the safe string is an extension to python299and not every library will work properly with it.300301302.. _builtin-filters:303304List of Builtin Filters305-----------------------306307.. jinjafilters::308309310.. _builtin-tests:311312List of Builtin Tests313---------------------314315bleh
modified:jinja2/filters.py+1 added
605 unmodified lines
606 '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 lines
modified:jinja2/tests.py+7 added-1 removed
110 unmodified lines
111 return False112 return True113114115def test_escaped(value):116 """Check if the value is escaped."""117 return hasattr(value, '__html__')118119120TESTS = {121 'odd': test_odd,122 'even': test_even,123 'divisibleby': test_divisibleby,
6 unmodified lines
130 '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}