Skip to content
Myr

api.rst

This file

Path

docs/api.rst

667 lines · 23.1 KiB

Last changed by

Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58

History of this file

Take it

The walk stopped after 200 commits: lines older than c0d40d3 point at it.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 1–16why, one step back
1API
2===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.

Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58

line 17why, one step back
17Even if you are creating templates from strings by using the constructor of

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 18–19why, one step back
18:class:`Template` class, an environment is created automatically for you,
19albeit a shared one.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 20–46why, one step back
20
21Most applications will create one :class:`Environment` object on application22initialization and use that to load templates. In some cases it's however23useful to have multiple environments side by side, if different configurations24are in use.2526The simplest way to configure Jinja2 to load templates for your application27looks roughly like this::2829 from jinja2 import Environment, PackageLoader30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))3132This will create a template environment with the default settings and a33loader that looks up the templates in the `templates` folder inside the34`yourapplication` python package. Different loaders are available35and you can also write your own if you want to load templates from a36database or other resources.3738To load a template from this environment you just have to call the39:meth:`get_template` method which then returns the loaded :class:`Template`::4041 template = env.get_template('mytemplate.html')4243To render it with some variables, just call the :meth:`render` method::4445 print template.render(the='variables', go='here')46

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 47–49why, one step back
47Using a template loader rather then passing strings to :class:`Template`
48or :meth:`Environment.from_string` has multiple advantages. Besides being49a lot easier to use it also enables template inheritance.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 50why, one step back
50

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

line 51why, one step back
51

end of line sequence is no configurableArmin Ronacherbefore adoptionf3c35c4

lines 52–59why, one step back
52Unicode
53-------5455Jinja2 is using unicode internally which means that you have to pass unicode56objects to the render function or bytestrings that only consist of ASCII57characters. Additionally newlines are normalized to one end of line58sequence which is per default UNIX style (``\n``).59

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 60–63why, one step back
60Python 2.x supports two ways of representing string objects. One is the
61`str` type and the other is the `unicode` type, both of which extend a type62called `basestring`. Unfortunately the default is `str` which should not63be used to store text based information unless only ASCII characters are

Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58

line 64why, one step back
64used. With Python 2.6 it is possible to make `unicode` the default on a per

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

line 65why, one step back
65module level and with Python 3 it will be the default.

end of line sequence is no configurableArmin Ronacherbefore adoptionf3c35c4

line 66why, one step back
66

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 67–91why, one step back
67To explicitly use a unicode string you have to prefix the string literal
68with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will69store the string as unicode by decoding the string with the character70encoding from the current Python module. If no encoding is specified this71defaults to 'ASCII' which means that you can't use any non ASCII identifier.7273To set a better module encoding add the following comment to the first or74second line of the Python module using the unicode literal::7576 # -*- coding: utf-8 -*-7778We recommend utf-8 as Encoding for Python modules and templates as it's79possible to represent every Unicode character in utf-8 and because it's80backwards compatible to ASCII. For Jinja2 the default encoding of templates81is assumed to be utf-8.8283It is not possible to use Jinja2 to process non unicode data. The reason84for this is that Jinja2 uses Unicode already on the language level. For85example Jinja2 treats the non-breaking space as valid whitespace inside86expressions which requires knowledge of the encoding or operating on an87unicode string.8889For more details about unicode in Python have a look at the excellent90`Unicode documentation`_.91

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 92–98why, one step back
92Another important thing is how Jinja2 is handling string literals in
93templates. A naive implementation would be using unicode strings for94all string literals but it turned out in the past that this is problematic95as some libraries are typechecking against `str` explicitly. For example96`datetime.strftime` does not accept unicode arguments. To not break it97completely Jinja2 is returning `str` for strings that fit into ASCII and98for everything else `unicode`:

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

line 99why, one step back
99

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 100–106why, one step back
100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
101>>> m.a102'foo'103>>> m.b104u'f\xf6\xf6'105106

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 107–108why, one step back
107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
108

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 109–111why, one step back
109High Level API
110--------------111

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 112–116why, one step back
112The high-level API is the API you will use in the application to load and
113render Jinja2 templates. The :ref:`low-level-api` on the other side is only114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115<jinja-extensions>`.116

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

line 117why, one step back
117.. autoclass:: Environment([options])

Added support for `Environment.compile_expression`.Armin Ronacherbefore adoptionba6e25a

line 118why, one step back
118 :members: from_string, get_template, join_path, extend, compile_expression

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 119–137why, one step back
119
120 .. attribute:: shared121122 If a template was created by using the :class:`Template` constructor123 an environment is created automatically. These environments are124 created as shared environments which means that multiple templates125 may have the same anonymous environment. For all shared environments126 this attribute is `True`, else `False`.127128 .. attribute:: sandboxed129130 If the environment is sandboxed this attribute is `True`. For the131 sandbox mode have a look at the documentation for the132 :class:`~jinja2.sandbox.SandboxedEnvironment`.133134 .. attribute:: filters135136 A dict of filters for this environment. As long as no template was137 loaded it's safe to add new filters or remove old. For custom filters

Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.Armin Ronacherbefore adoptiond1ff858

lines 138–139why, one step back
138 see :ref:`writing-filters`. For valid filter names have a look at
139 :ref:`identifier-naming`.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 140–144why, one step back
140
141 .. attribute:: tests142143 A dict of test functions for this environment. As long as no144 template was loaded it's safe to modify this dict. For custom tests

Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.Armin Ronacherbefore adoptiond1ff858

lines 145–146why, one step back
145 see :ref:`writing-tests`. For valid test names have a look at
146 :ref:`identifier-naming`.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 147–150why, one step back
147
148 .. attribute:: globals149150 A dict of global variables. These variables are always available

removed unused importsArmin Ronacherbefore adoption981cbf6

line 151why, one step back
151 in a template. As long as no template was loaded it's safe

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 152why, one step back
152 to modify this dict. For more details see :ref:`global-namespace`.

Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.Armin Ronacherbefore adoptiond1ff858

line 153why, one step back
153 For valid object names have a look at :ref:`identifier-naming`.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 154why, one step back
154

some documentation updatesArmin Ronacherbefore adoptioned98cac

line 155why, one step back
155 .. automethod:: overlay([options])

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 156why, one step back
156

data files are optional nowArmin Ronacherbefore adoption58f351d

line 157why, one step back
157 .. method:: undefined([hint, obj, name, exc])

some documentation updatesArmin Ronacherbefore adoptioned98cac

line 158why, one step back
158

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 159–163why, one step back
159 Creates a new :class:`Undefined` object for `name`. This is useful
160 for filters or functions that may return undefined objects for161 some operations. All parameters except of `hint` should be provided162 as keyword parameters for better readability. The `hint` is used as163 error message for the exception if provided, otherwise the error

Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58

line 164why, one step back
164 message will be generated from `obj` and `name` automatically. The exception

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 165–192why, one step back
165 provided as `exc` is raised if something with the generated undefined
166 object is done that the undefined object does not allow. The default167 exception is :exc:`UndefinedError`. If a `hint` is provided the168 `name` may be ommited.169170 The most common way to create an undefined object is by providing171 a name only::172173 return environment.undefined(name='some_name')174175 This means that the name `some_name` is not defined. If the name176 was from an attribute of an object it makes sense to tell the177 undefined object the holder object to improve the error message::178179 if not hasattr(obj, 'attr'):180 return environment.undefined(obj=obj, name='attr')181182 For a more complex example you can provide a hint. For example183 the :func:`first` filter creates an undefined object that way::184185 return environment.undefined('no first item, sequence was empty') 186187 If it the `name` or `obj` is known (for example because an attribute188 was accessed) it shold be passed to the undefined object, even if189 a custom `hint` is provided. This gives undefined objects the190 possibility to enhance the error message.191192.. autoclass:: Template

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

line 193why, one step back
193 :members: module, make_module

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 194–196why, one step back
194
195 .. attribute:: globals196

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 197–199why, one step back
197 The dict with the globals of that template. It's unsafe to modify
198 this dict as it may be shared with other templates or the environment199 that loaded the template.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 200–202why, one step back
200
201 .. attribute:: name202

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 203–205why, one step back
203 The loading name of the template. If the template was loaded from a
204 string this is `None`.205

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 206–210why, one step back
206 .. attribute:: filename
207208 The filename of the template on the file system if it was loaded from209 there. Otherwise this is `None`.210

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 211–215why, one step back
211 .. automethod:: render([context])
212213 .. automethod:: generate([context])214215 .. automethod:: stream([context])

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 216–217why, one step back
216
217

more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e

line 218why, one step back
218.. autoclass:: jinja2.environment.TemplateStream()

Added `TemplateStream.dump`.Armin Ronacherbefore adoption74b5106

line 219why, one step back
219 :members: disable_buffering, enable_buffering, dump

Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.Armin Ronacherbefore adoptiond1ff858

lines 220–224why, one step back
220
221222.. _identifier-naming:223224Notes on Identifiers

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

line 225why, one step back
225--------------------

Backed out changeset 6afb554797b6, which added unicode identifier support. This doesn't work in reality under Python 2.6 properly.Armin Ronacherbefore adoptiond1ff858

lines 226–237why, one step back
226
227Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to228match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters229are currently not allowed. This limitation will probably go away as soon as230unicode identifiers are fully specified for Python 3.231232Filters and tests are looked up in separate namespaces and have slightly233modified identifier syntax. Filters and tests may contain dots to group234filters and tests by topic. For example it's perfectly valid to add a235function into the filter dict and call it `to.unicode`. The regular236expression for filter and test identifiers is237``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 238–252why, one step back
238
239240Undefined Types241---------------242243These classes can be used as undefined types. The :class:`Environment`244constructor takes an `undefined` parameter that can be one of those classes245or a custom subclass of :class:`Undefined`. Whenever the template engine is246unable to look up a name or access an attribute one of those objects is247created and returned. Some operations on undefined values are then allowed,248others fail.249250The closest to regular Python behavior is the `StrictUndefined` which251disallows all operations beside testing if it's an undefined object.252

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 253why, one step back
253.. autoclass:: jinja2.Undefined()

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 254why, one step back
254

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 255–280why, one step back
255 .. attribute:: _undefined_hint
256257 Either `None` or an unicode string with the error message for258 the undefined object.259260 .. attribute:: _undefined_obj261262 Either `None` or the owner object that caused the undefined object263 to be created (for example because an attribute does not exist).264265 .. attribute:: _undefined_name266267 The name for the undefined variable / attribute or just `None`268 if no such information exists.269270 .. attribute:: _undefined_exception271272 The exception that the undefined object wants to raise. This273 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.274275 .. method:: _fail_with_undefined_error(\*args, \**kwargs)276277 When called with any arguments this method raises278 :attr:`_undefined_exception` with an error message generated279 from the undefined hints stored on the undefined object.280

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 281why, one step back
281.. autoclass:: jinja2.DebugUndefined()

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 282why, one step back
282

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 283why, one step back
283.. autoclass:: jinja2.StrictUndefined()

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 284why, one step back
284

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

line 285why, one step back
285Undefined objects are created by calling :attr:`undefined`.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 286why, one step back
286

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

line 287why, one step back
287.. admonition:: Implementation

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

line 288why, one step back
288

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 289–301why, one step back
289 :class:`Undefined` objects are implemented by overriding the special
290 `__underscore__` methods. For example the default :class:`Undefined`291 class implements `__unicode__` in a way that it returns an empty292 string, however `__int__` and others still fail with an exception. To293 allow conversion to int by returning ``0`` you can implement your own::294295 class NullUndefined(Undefined):296 def __int__(self):297 return 0298 def __float__(self):299 return 0.0300301 To disallow a method, just override it and raise

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 302–306why, one step back
302 :attr:`~Undefined._undefined_exception`. Because this is a very common
303 idom in undefined objects there is the helper method304 :meth:`~Undefined._fail_with_undefined_error` that does the error raising305 automatically. Here a class that works like the regular :class:`Undefined`306 but chokes on iteration::

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 307–311why, one step back
307
308 class NonIterableUndefined(Undefined):309 __iter__ = Undefined._fail_with_undefined_error310311

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 312–314why, one step back
312The Context
313-----------314

more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e

line 315why, one step back
315.. autoclass:: jinja2.runtime.Context()

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281

line 316why, one step back
316 :members: resolve, get_exported, get_all

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 317–321why, one step back
317
318 .. attribute:: parent319320 A dict of read only, global variables the template looks up. These321 can either come from another :class:`Context`, from the

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 322–324why, one step back
322 :attr:`Environment.globals` or :attr:`Template.globals` or points
323 to a dict created by combining the globals with the variables324 passed to the render function. It must not be altered.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 325–354why, one step back
325
326 .. attribute:: vars327328 The template local variables. This list contains environment and329 context functions from the :attr:`parent` scope as well as local330 modifications and exported variables from the template. The template331 will modify this dict during template evaluation but filters and332 context functions are not allowed to modify it.333334 .. attribute:: environment335336 The environment that loaded the template.337338 .. attribute:: exported_vars339340 This set contains all the names the template exports. The values for341 the names are in the :attr:`vars` dict. In order to get a copy of the342 exported variables as dict, :meth:`get_exported` can be used.343344 .. attribute:: name345346 The load name of the template owning this context.347348 .. attribute:: blocks349350 A dict with the current mapping of blocks in the template. The keys351 in this dict are the names of the blocks, and the values a list of352 blocks registered. The last item in each list is the current active353 block (latest in the inheritance chain).354

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

line 355why, one step back
355 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 356why, one step back
356

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 357–369why, one step back
357
358.. admonition:: Implementation359360 Context is immutable for the same reason Python's frame locals are361 immutable inside functions. Both Jinja2 and Python are not using the362 context / frame locals as data storage for variables but only as primary363 data source.364365 When a template accesses a variable the template does not define, Jinja2366 looks up the variable in the context, after that the variable is treated367 as if it was defined in the template.368369

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 370–371why, one step back
370.. _loaders:
371

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 372–381why, one step back
372Loaders
373-------374375Loaders are responsible for loading templates from a resource such as the376file system. The environment will keep the compiled modules in memory like377Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in378size by default and templates are automatically reloaded.379All loaders are subclasses of :class:`BaseLoader`. If you want to create your380own loader, subclass :class:`BaseLoader` and override `get_source`.381

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 382why, one step back
382.. autoclass:: jinja2.BaseLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 383–386why, one step back
383 :members: get_source, load
384385Here a list of the builtin loaders Jinja2 provides:386

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 387why, one step back
387.. autoclass:: jinja2.FileSystemLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 388why, one step back
388

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 389why, one step back
389.. autoclass:: jinja2.PackageLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 390why, one step back
390

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 391why, one step back
391.. autoclass:: jinja2.DictLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 392why, one step back
392

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 393why, one step back
393.. autoclass:: jinja2.FunctionLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 394why, one step back
394

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 395why, one step back
395.. autoclass:: jinja2.PrefixLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 396why, one step back
396

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 397why, one step back
397.. autoclass:: jinja2.ChoiceLoader

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 398–399why, one step back
398
399

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

lines 400–438why, one step back
400.. _bytecode-cache:
401402Bytecode Cache403--------------404405Jinja 2.1 and higher support external bytecode caching. Bytecode caches make406it possible to store the generated bytecode on the file system or a different407location to avoid parsing the templates on first use.408409This is especially useful if you have a web application that is initialized on410the first request and Jinja compiles many templates at once which slows down411the application.412413To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.414415.. autoclass:: jinja2.BytecodeCache416 :members: load_bytecode, dump_bytecode, clear417418.. autoclass:: jinja2.bccache.Bucket419 :members: write_bytecode, load_bytecode, bytecode_from_string,420 bytecode_to_string, reset421422 .. attribute:: environment423424 The :class:`Environment` that created the bucket.425426 .. attribute:: key427428 The unique cache key for this bucket429430 .. attribute:: code431432 The bytecode if it's loaded, otherwise `None`.433434435Builtin bytecode caches:436437.. autoclass:: jinja2.FileSystemBytecodeCache438

Fixed bytecode cache and added support for memcached (tests still missing)Armin Ronacherbefore adoptionaa1d17d

lines 439–440why, one step back
439.. autoclass:: jinja2.MemcachedBytecodeCache
440

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 441why, one step back
441

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 442–447why, one step back
442Utilities
443---------444445These helper functions and classes are useful if you add custom filters or446functions to a Jinja2 environment.447

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 448why, one step back
448.. autofunction:: jinja2.environmentfilter

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 449why, one step back
449

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 450why, one step back
450.. autofunction:: jinja2.contextfilter

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 451why, one step back
451

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 452why, one step back
452.. autofunction:: jinja2.environmentfunction

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 453why, one step back
453

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 454why, one step back
454.. autofunction:: jinja2.contextfunction

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 455–457why, one step back
455
456.. function:: escape(s)457

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 458–461why, one step back
458 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
459 to HTML-safe sequences. Use this if you need to display text that might460 contain such characters in HTML. This function will not escaped objects461 that do have an HTML representation such as already escaped data.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 462why, one step back
462

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 463–464why, one step back
463 The return value is a :class:`Markup` string.
464

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 465why, one step back
465.. autofunction:: jinja2.clear_caches

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 466why, one step back
466

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 467why, one step back
467.. autofunction:: jinja2.is_undefined

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

line 468why, one step back
468

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 469why, one step back
469.. autoclass:: jinja2.Markup([string])

data files are optional nowArmin Ronacherbefore adoption58f351d

line 470why, one step back
470 :members: escape, unescape, striptags

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 471why, one step back
471

data files are optional nowArmin Ronacherbefore adoption58f351d

line 472why, one step back
472.. admonition:: Note

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 473why, one step back
473

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 474–478why, one step back
474 The Jinja2 :class:`Markup` class is compatible with at least Pylons and
475 Genshi. It's expected that more template engines and framework will pick476 up the `__html__` concept soon.477478

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 479–481why, one step back
479Exceptions
480----------481

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 482why, one step back
482.. autoexception:: jinja2.TemplateError

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 483why, one step back
483

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 484why, one step back
484.. autoexception:: jinja2.UndefinedError

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 485why, one step back
485

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 486why, one step back
486.. autoexception:: jinja2.TemplateNotFound

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 487why, one step back
487

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 488why, one step back
488.. autoexception:: jinja2.TemplateSyntaxError

end of line sequence is no configurableArmin Ronacherbefore adoptionf3c35c4

lines 489–509why, one step back
489
490 .. attribute:: message491492 The error message as utf-8 bytestring.493494 .. attribute:: lineno495496 The line number where the error occurred497498 .. attribute:: name499500 The load name for the template as unicode string.501502 .. attribute:: filename503504 The filename that loaded the template as bytestring in the encoding505 of the file system (most likely utf-8 or mbcs on Windows systems).506507 The reason why the filename and error message are bytestrings and not508 unicode strings is that Python 2.x is not using unicode for exceptions509 and tracebacks as well as the compiler. This will change with Python 3.

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 510why, one step back
510

Improved bbcache and documented it.Armin Ronacherbefore adoptiona816bf4

line 511why, one step back
511.. autoexception:: jinja2.TemplateAssertionError

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 512–542why, one step back
512
513514.. _writing-filters:515516Custom Filters517--------------518519Custom filters are just regular Python functions that take the left side of520the filter as first argument and the the arguments passed to the filter as521extra arguments or keyword arguments.522523For example in the filter ``{{ 42|myfilter(23) }}`` the function would be524called with ``myfilter(42, 23)``. Here for example a simple filter that can525be applied to datetime objects to format them::526527 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):528 return value.strftime(format)529530You can register it on the template environment by updating the531:attr:`~Environment.filters` dict on the environment::532533 environment.filters['datetimeformat'] = datetimeformat534535Inside the template it can then be used as follows:536537.. sourcecode:: jinja538539 written on: {{ article.pub_date|datetimeformat }}540 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}541542Filters can also be passed the current template context or environment. This

Applied documentation patches by Clemens Hermann.Armin Ronacherbefore adoption0aa0f58

line 543why, one step back
543is useful if a filter wants to return an undefined value or check the current

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 544–572why, one step back
544:attr:`~Environment.autoescape` setting. For this purpose two decorators
545exist: :func:`environmentfilter` and :func:`contextfilter`.546547Here a small example filter that breaks a text into HTML line breaks and548paragraphs and marks the return value as safe HTML string if autoescaping is549enabled::550551 import re552 from jinja2 import environmentfilter, Markup, escape553554 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')555556 @environmentfilter557 def nl2br(environment, value):558 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')559 for p in _paragraph_re.split(escape(value)))560 if environment.autoescape:561 result = Markup(result)562 return result563564Context filters work the same just that the first argument is the current565active :class:`Context` rather then the environment.566567568.. _writing-tests:569570Custom Tests571------------572

filter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55

line 573why, one step back
573Tests work like filters just that there is no way for a test to get access

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

line 574why, one step back
574to the environment or context and that they can't be chained. The return

filter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55

line 575why, one step back
575value of a test should be `True` or `False`. The purpose of a test is to

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 576–578why, one step back
576give the template designers the possibility to perform type and conformability
577checks.578

filter -> test in the tests section (i feel so embarrassed).Armin Ronacherbefore adoptiona5d8f55

line 579why, one step back
579Here a simple test that checks if a variable is a prime number::

using a table for _speedups escapeMickaël Guérinbefore adoptionc0d40d3

lines 580–612why, one step back
580
581 import math582583 def is_prime(n):584 if n == 2:585 return True586 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):587 if n % i == 0:588 return False589 return True590 591592You can register it on the template environment by updating the593:attr:`~Environment.tests` dict on the environment::594595 environment.tests['prime'] = is_prime596597A template designer can then use the test like this:598599.. sourcecode:: jinja600601 {% if 42 is prime %}602 42 is a prime number603 {% else %}604 42 is not a prime number605 {% endif %}606607608.. _global-namespace:609610The Global Namespace611--------------------612

removed unused importsArmin Ronacherbefore adoption981cbf6

lines 613–618why, one step back
613Variables stored in the :attr:`Environment.globals` dict are special as they
614are available for imported templates too, even if they are imported without615context. This is the place where you can put variables and functions616that should be available all the time. Additionally :attr:`Template.globals`617exist that are variables available to a specific template that are available618to all :meth:`~Template.render` calls.

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 619–620why, one step back
619
620

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 621–622why, one step back
621.. _low-level-api:
622

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 623–627why, one step back
623Low Level API
624-------------625626The low level API exposes functionality that can be useful to understand some627implementation details, debugging purposes or advanced :ref:`extension

fixed a bug in error reporting and some small documentation updatesArmin Ronacherbefore adoption61a5a24

lines 628–629why, one step back
628<jinja-extensions>` techniques. Unless you know exactly what you are doing we
629don't recommend using any of those.

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 630–634why, one step back
630
631.. automethod:: Environment.lex632633.. automethod:: Environment.parse634

added support for token stream filtering and preprocessing.Armin Ronacherbefore adoption9ad96e7

lines 635–636why, one step back
635.. automethod:: Environment.preprocess
636

even more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7

lines 637–660why, one step back
637.. automethod:: Template.new_context
638639.. method:: Template.root_render_func(context)640641 This is the low level render function. It's passed a :class:`Context`642 that has to be created by :meth:`new_context` of the same template or643 a compatible template. This render function is generated by the644 compiler from the template code and returns a generator that yields645 unicode strings.646647 If an exception in the template code happens the template engine will648 not rewrite the exception but pass through the original one. As a649 matter of fact this function should only be called from within a650 :meth:`render` / :meth:`generate` / :meth:`stream` call.651652.. attribute:: Template.blocks653654 A dict of block render functions. Each of these functions works exactly655 like the :meth:`root_render_func` with the same limitations.656657.. attribute:: Template.is_up_to_date658659 This attribute is `False` if there is a newer version of the template660 available, otherwise `True`.

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 661–663why, one step back
661
662.. admonition:: Note663

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 664–667why, one step back
664 The low-level API is fragile. Future Jinja2 versions will try not to
665 change it in a backwards incompatible way but modifications in the Jinja2666 core may shine through. For example if Jinja2 introduces a new AST node667 in later versions that may be returned by :meth:`~Environment.parse`.