blob: d6d1e20a2ddb6761fa204a4b744c5cf66e17a3e6 [file] [log] [blame]
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02001API
2===
3
4.. module:: jinja2
5 :synopsis: public Jinja2 API
6
7This document describes the API to Jinja2 and not the template language. It
8will be most useful as reference to those implementing the template interface
9to the application and not those who are creating Jinja2 templates.
10
11Basics
12------
13
14Jinja2 uses a central object called the template :class:`Environment`.
15Instances of this class are used to store the configuration, global objects
16and are used to load templates from the file system or other locations.
Armin Ronacher0aa0f582009-03-18 01:01:36 +010017Even if you are creating templates from strings by using the constructor of
Armin Ronacher61a5a242008-05-26 12:07:44 +020018:class:`Template` class, an environment is created automatically for you,
19albeit a shared one.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020020
21Most applications will create one :class:`Environment` object on application
22initialization and use that to load templates. In some cases it's however
23useful to have multiple environments side by side, if different configurations
24are in use.
25
26The simplest way to configure Jinja2 to load templates for your application
27looks roughly like this::
28
29 from jinja2 import Environment, PackageLoader
30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
31
32This will create a template environment with the default settings and a
33loader that looks up the templates in the `templates` folder inside the
34`yourapplication` python package. Different loaders are available
35and you can also write your own if you want to load templates from a
36database or other resources.
37
38To load a template from this environment you just have to call the
39:meth:`get_template` method which then returns the loaded :class:`Template`::
40
41 template = env.get_template('mytemplate.html')
42
43To render it with some variables, just call the :meth:`render` method::
44
45 print template.render(the='variables', go='here')
46
Armin Ronacher61a5a242008-05-26 12:07:44 +020047Using a template loader rather then passing strings to :class:`Template`
48or :meth:`Environment.from_string` has multiple advantages. Besides being
49a lot easier to use it also enables template inheritance.
50
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020051
Armin Ronacherf3c35c42008-05-23 23:18:14 +020052Unicode
53-------
54
55Jinja2 is using unicode internally which means that you have to pass unicode
56objects to the render function or bytestrings that only consist of ASCII
57characters. Additionally newlines are normalized to one end of line
58sequence which is per default UNIX style (``\n``).
59
Armin Ronacher61a5a242008-05-26 12:07:44 +020060Python 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 type
62called `basestring`. Unfortunately the default is `str` which should not
63be used to store text based information unless only ASCII characters are
Armin Ronacher0aa0f582009-03-18 01:01:36 +010064used. With Python 2.6 it is possible to make `unicode` the default on a per
Armin Ronacher61a5a242008-05-26 12:07:44 +020065module level and with Python 3 it will be the default.
66
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 will
69store the string as unicode by decoding the string with the character
70encoding from the current Python module. If no encoding is specified this
71defaults to 'ASCII' which means that you can't use any non ASCII identifier.
72
73To set a better module encoding add the following comment to the first or
74second line of the Python module using the unicode literal::
75
76 # -*- coding: utf-8 -*-
77
78We recommend utf-8 as Encoding for Python modules and templates as it's
79possible to represent every Unicode character in utf-8 and because it's
80backwards compatible to ASCII. For Jinja2 the default encoding of templates
81is assumed to be utf-8.
82
83It is not possible to use Jinja2 to process non unicode data. The reason
84for this is that Jinja2 uses Unicode already on the language level. For
85example Jinja2 treats the non-breaking space as valid whitespace inside
86expressions which requires knowledge of the encoding or operating on an
87unicode string.
88
89For more details about unicode in Python have a look at the excellent
90`Unicode documentation`_.
91
Armin Ronacher58f351d2008-05-28 21:30:14 +020092Another important thing is how Jinja2 is handling string literals in
93templates. A naive implementation would be using unicode strings for
94all string literals but it turned out in the past that this is problematic
95as some libraries are typechecking against `str` explicitly. For example
96`datetime.strftime` does not accept unicode arguments. To not break it
97completely Jinja2 is returning `str` for strings that fit into ASCII and
98for everything else `unicode`:
99
100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
101>>> m.a
102'foo'
103>>> m.b
104u'f\xf6\xf6'
105
Armin Ronacher61a5a242008-05-26 12:07:44 +0200106
107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200108
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200109High Level API
110--------------
111
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200112The 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 only
114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
115<jinja-extensions>`.
116
Armin Ronacher5411ce72008-05-25 11:36:22 +0200117.. autoclass:: Environment([options])
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100118 :members: from_string, get_template, select_template,
119 get_or_select_template, join_path, extend, compile_expression
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200120
121 .. attribute:: shared
122
123 If a template was created by using the :class:`Template` constructor
124 an environment is created automatically. These environments are
125 created as shared environments which means that multiple templates
126 may have the same anonymous environment. For all shared environments
127 this attribute is `True`, else `False`.
128
129 .. attribute:: sandboxed
130
131 If the environment is sandboxed this attribute is `True`. For the
132 sandbox mode have a look at the documentation for the
133 :class:`~jinja2.sandbox.SandboxedEnvironment`.
134
135 .. attribute:: filters
136
137 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +0200138 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200139 see :ref:`writing-filters`. For valid filter names have a look at
140 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200141
142 .. attribute:: tests
143
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200144 A dict of test functions for this environment. As long as no
145 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200146 see :ref:`writing-tests`. For valid test names have a look at
147 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200148
149 .. attribute:: globals
150
151 A dict of global variables. These variables are always available
Armin Ronacher981cbf62008-05-13 09:12:27 +0200152 in a template. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +0200153 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200154 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200155
Armin Ronachered98cac2008-05-07 08:42:11 +0200156 .. automethod:: overlay([options])
157
Armin Ronacher58f351d2008-05-28 21:30:14 +0200158 .. method:: undefined([hint, obj, name, exc])
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200159
Armin Ronacher5411ce72008-05-25 11:36:22 +0200160 Creates a new :class:`Undefined` object for `name`. This is useful
161 for filters or functions that may return undefined objects for
162 some operations. All parameters except of `hint` should be provided
163 as keyword parameters for better readability. The `hint` is used as
164 error message for the exception if provided, otherwise the error
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100165 message will be generated from `obj` and `name` automatically. The exception
Armin Ronacher5411ce72008-05-25 11:36:22 +0200166 provided as `exc` is raised if something with the generated undefined
167 object is done that the undefined object does not allow. The default
168 exception is :exc:`UndefinedError`. If a `hint` is provided the
169 `name` may be ommited.
170
171 The most common way to create an undefined object is by providing
172 a name only::
173
174 return environment.undefined(name='some_name')
175
176 This means that the name `some_name` is not defined. If the name
177 was from an attribute of an object it makes sense to tell the
178 undefined object the holder object to improve the error message::
179
180 if not hasattr(obj, 'attr'):
181 return environment.undefined(obj=obj, name='attr')
182
183 For a more complex example you can provide a hint. For example
184 the :func:`first` filter creates an undefined object that way::
185
186 return environment.undefined('no first item, sequence was empty')
187
188 If it the `name` or `obj` is known (for example because an attribute
189 was accessed) it shold be passed to the undefined object, even if
190 a custom `hint` is provided. This gives undefined objects the
191 possibility to enhance the error message.
192
193.. autoclass:: Template
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200194 :members: module, make_module
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200195
Armin Ronacher7259c762008-04-30 13:03:59 +0200196 .. attribute:: globals
197
Armin Ronachered98cac2008-05-07 08:42:11 +0200198 The dict with the globals of that template. It's unsafe to modify
199 this dict as it may be shared with other templates or the environment
200 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200201
202 .. attribute:: name
203
Armin Ronachered98cac2008-05-07 08:42:11 +0200204 The loading name of the template. If the template was loaded from a
205 string this is `None`.
206
Armin Ronacher5411ce72008-05-25 11:36:22 +0200207 .. attribute:: filename
208
209 The filename of the template on the file system if it was loaded from
210 there. Otherwise this is `None`.
211
Armin Ronachered98cac2008-05-07 08:42:11 +0200212 .. automethod:: render([context])
213
214 .. automethod:: generate([context])
215
216 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200217
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200218
Armin Ronacher6df604e2008-05-23 22:18:38 +0200219.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher74b51062008-06-17 11:28:59 +0200220 :members: disable_buffering, enable_buffering, dump
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200221
222
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200223.. _identifier-naming:
224
225Notes on Identifiers
Armin Ronacher5411ce72008-05-25 11:36:22 +0200226--------------------
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200227
228Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
229match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
230are currently not allowed. This limitation will probably go away as soon as
231unicode identifiers are fully specified for Python 3.
232
233Filters and tests are looked up in separate namespaces and have slightly
234modified identifier syntax. Filters and tests may contain dots to group
235filters and tests by topic. For example it's perfectly valid to add a
236function into the filter dict and call it `to.unicode`. The regular
237expression for filter and test identifiers is
238``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
239
240
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200241Undefined Types
242---------------
243
244These classes can be used as undefined types. The :class:`Environment`
245constructor takes an `undefined` parameter that can be one of those classes
246or a custom subclass of :class:`Undefined`. Whenever the template engine is
247unable to look up a name or access an attribute one of those objects is
248created and returned. Some operations on undefined values are then allowed,
249others fail.
250
251The closest to regular Python behavior is the `StrictUndefined` which
252disallows all operations beside testing if it's an undefined object.
253
Armin Ronachera816bf42008-09-17 21:28:01 +0200254.. autoclass:: jinja2.Undefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200255
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200256 .. attribute:: _undefined_hint
257
258 Either `None` or an unicode string with the error message for
259 the undefined object.
260
261 .. attribute:: _undefined_obj
262
263 Either `None` or the owner object that caused the undefined object
264 to be created (for example because an attribute does not exist).
265
266 .. attribute:: _undefined_name
267
268 The name for the undefined variable / attribute or just `None`
269 if no such information exists.
270
271 .. attribute:: _undefined_exception
272
273 The exception that the undefined object wants to raise. This
274 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
275
276 .. method:: _fail_with_undefined_error(\*args, \**kwargs)
277
278 When called with any arguments this method raises
279 :attr:`_undefined_exception` with an error message generated
280 from the undefined hints stored on the undefined object.
281
Armin Ronachera816bf42008-09-17 21:28:01 +0200282.. autoclass:: jinja2.DebugUndefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200283
Armin Ronachera816bf42008-09-17 21:28:01 +0200284.. autoclass:: jinja2.StrictUndefined()
Armin Ronacher5411ce72008-05-25 11:36:22 +0200285
286Undefined objects are created by calling :attr:`undefined`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200287
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200288.. admonition:: Implementation
289
290 :class:`Undefined` objects are implemented by overriding the special
291 `__underscore__` methods. For example the default :class:`Undefined`
292 class implements `__unicode__` in a way that it returns an empty
293 string, however `__int__` and others still fail with an exception. To
294 allow conversion to int by returning ``0`` you can implement your own::
295
296 class NullUndefined(Undefined):
297 def __int__(self):
298 return 0
299 def __float__(self):
300 return 0.0
301
302 To disallow a method, just override it and raise
Armin Ronacher58f351d2008-05-28 21:30:14 +0200303 :attr:`~Undefined._undefined_exception`. Because this is a very common
304 idom in undefined objects there is the helper method
305 :meth:`~Undefined._fail_with_undefined_error` that does the error raising
306 automatically. Here a class that works like the regular :class:`Undefined`
307 but chokes on iteration::
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200308
309 class NonIterableUndefined(Undefined):
310 __iter__ = Undefined._fail_with_undefined_error
311
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200312
Armin Ronacher7259c762008-04-30 13:03:59 +0200313The Context
314-----------
315
Armin Ronacher6df604e2008-05-23 22:18:38 +0200316.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200317 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200318
319 .. attribute:: parent
320
321 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200322 can either come from another :class:`Context`, from the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200323 :attr:`Environment.globals` or :attr:`Template.globals` or points
324 to a dict created by combining the globals with the variables
325 passed to the render function. It must not be altered.
Armin Ronacher7259c762008-04-30 13:03:59 +0200326
327 .. attribute:: vars
328
329 The template local variables. This list contains environment and
330 context functions from the :attr:`parent` scope as well as local
331 modifications and exported variables from the template. The template
332 will modify this dict during template evaluation but filters and
333 context functions are not allowed to modify it.
334
335 .. attribute:: environment
336
337 The environment that loaded the template.
338
339 .. attribute:: exported_vars
340
341 This set contains all the names the template exports. The values for
342 the names are in the :attr:`vars` dict. In order to get a copy of the
343 exported variables as dict, :meth:`get_exported` can be used.
344
345 .. attribute:: name
346
347 The load name of the template owning this context.
348
349 .. attribute:: blocks
350
351 A dict with the current mapping of blocks in the template. The keys
352 in this dict are the names of the blocks, and the values a list of
353 blocks registered. The last item in each list is the current active
354 block (latest in the inheritance chain).
355
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200356 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
357
358
359.. admonition:: Implementation
360
361 Context is immutable for the same reason Python's frame locals are
362 immutable inside functions. Both Jinja2 and Python are not using the
363 context / frame locals as data storage for variables but only as primary
364 data source.
365
366 When a template accesses a variable the template does not define, Jinja2
367 looks up the variable in the context, after that the variable is treated
368 as if it was defined in the template.
369
Armin Ronacher7259c762008-04-30 13:03:59 +0200370
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200371.. _loaders:
372
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200373Loaders
374-------
375
376Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200377file system. The environment will keep the compiled modules in memory like
378Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
379size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200380All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200381own loader, subclass :class:`BaseLoader` and override `get_source`.
382
Armin Ronachera816bf42008-09-17 21:28:01 +0200383.. autoclass:: jinja2.BaseLoader
Armin Ronachercda43df2008-05-03 17:10:05 +0200384 :members: get_source, load
385
386Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200387
Armin Ronachera816bf42008-09-17 21:28:01 +0200388.. autoclass:: jinja2.FileSystemLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200389
Armin Ronachera816bf42008-09-17 21:28:01 +0200390.. autoclass:: jinja2.PackageLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200391
Armin Ronachera816bf42008-09-17 21:28:01 +0200392.. autoclass:: jinja2.DictLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200393
Armin Ronachera816bf42008-09-17 21:28:01 +0200394.. autoclass:: jinja2.FunctionLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200395
Armin Ronachera816bf42008-09-17 21:28:01 +0200396.. autoclass:: jinja2.PrefixLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200397
Armin Ronachera816bf42008-09-17 21:28:01 +0200398.. autoclass:: jinja2.ChoiceLoader
399
400
401.. _bytecode-cache:
402
403Bytecode Cache
404--------------
405
406Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
407it possible to store the generated bytecode on the file system or a different
408location to avoid parsing the templates on first use.
409
410This is especially useful if you have a web application that is initialized on
411the first request and Jinja compiles many templates at once which slows down
412the application.
413
414To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.
415
416.. autoclass:: jinja2.BytecodeCache
417 :members: load_bytecode, dump_bytecode, clear
418
419.. autoclass:: jinja2.bccache.Bucket
420 :members: write_bytecode, load_bytecode, bytecode_from_string,
421 bytecode_to_string, reset
422
423 .. attribute:: environment
424
425 The :class:`Environment` that created the bucket.
426
427 .. attribute:: key
428
429 The unique cache key for this bucket
430
431 .. attribute:: code
432
433 The bytecode if it's loaded, otherwise `None`.
434
435
436Builtin bytecode caches:
437
438.. autoclass:: jinja2.FileSystemBytecodeCache
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200439
Armin Ronacheraa1d17d2008-09-18 18:09:06 +0200440.. autoclass:: jinja2.MemcachedBytecodeCache
441
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200442
443Utilities
444---------
445
446These helper functions and classes are useful if you add custom filters or
447functions to a Jinja2 environment.
448
Armin Ronachera816bf42008-09-17 21:28:01 +0200449.. autofunction:: jinja2.environmentfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200450
Armin Ronachera816bf42008-09-17 21:28:01 +0200451.. autofunction:: jinja2.contextfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200452
Armin Ronachera816bf42008-09-17 21:28:01 +0200453.. autofunction:: jinja2.environmentfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200454
Armin Ronachera816bf42008-09-17 21:28:01 +0200455.. autofunction:: jinja2.contextfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200456
457.. function:: escape(s)
458
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200459 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
460 to HTML-safe sequences. Use this if you need to display text that might
461 contain such characters in HTML. This function will not escaped objects
462 that do have an HTML representation such as already escaped data.
463
464 The return value is a :class:`Markup` string.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200465
Armin Ronachera816bf42008-09-17 21:28:01 +0200466.. autofunction:: jinja2.clear_caches
Armin Ronacher187bde12008-05-01 18:19:16 +0200467
Armin Ronachera816bf42008-09-17 21:28:01 +0200468.. autofunction:: jinja2.is_undefined
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200469
Armin Ronachera816bf42008-09-17 21:28:01 +0200470.. autoclass:: jinja2.Markup([string])
Armin Ronacher58f351d2008-05-28 21:30:14 +0200471 :members: escape, unescape, striptags
472
473.. admonition:: Note
474
475 The Jinja2 :class:`Markup` class is compatible with at least Pylons and
476 Genshi. It's expected that more template engines and framework will pick
477 up the `__html__` concept soon.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200478
479
480Exceptions
481----------
482
Armin Ronachera816bf42008-09-17 21:28:01 +0200483.. autoexception:: jinja2.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200484
Armin Ronachera816bf42008-09-17 21:28:01 +0200485.. autoexception:: jinja2.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200486
Armin Ronachera816bf42008-09-17 21:28:01 +0200487.. autoexception:: jinja2.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200488
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100489.. autoexception:: jinja2.TemplatesNotFound
490
Armin Ronachera816bf42008-09-17 21:28:01 +0200491.. autoexception:: jinja2.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200492
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200493 .. attribute:: message
494
495 The error message as utf-8 bytestring.
496
497 .. attribute:: lineno
498
499 The line number where the error occurred
500
501 .. attribute:: name
502
503 The load name for the template as unicode string.
504
505 .. attribute:: filename
506
507 The filename that loaded the template as bytestring in the encoding
508 of the file system (most likely utf-8 or mbcs on Windows systems).
509
510 The reason why the filename and error message are bytestrings and not
511 unicode strings is that Python 2.x is not using unicode for exceptions
512 and tracebacks as well as the compiler. This will change with Python 3.
513
Armin Ronachera816bf42008-09-17 21:28:01 +0200514.. autoexception:: jinja2.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200515
516
517.. _writing-filters:
518
519Custom Filters
520--------------
521
522Custom filters are just regular Python functions that take the left side of
523the filter as first argument and the the arguments passed to the filter as
524extra arguments or keyword arguments.
525
526For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
527called with ``myfilter(42, 23)``. Here for example a simple filter that can
528be applied to datetime objects to format them::
529
530 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
531 return value.strftime(format)
532
533You can register it on the template environment by updating the
534:attr:`~Environment.filters` dict on the environment::
535
536 environment.filters['datetimeformat'] = datetimeformat
537
538Inside the template it can then be used as follows:
539
540.. sourcecode:: jinja
541
542 written on: {{ article.pub_date|datetimeformat }}
543 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
544
545Filters can also be passed the current template context or environment. This
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100546is useful if a filter wants to return an undefined value or check the current
Armin Ronacher7259c762008-04-30 13:03:59 +0200547:attr:`~Environment.autoescape` setting. For this purpose two decorators
548exist: :func:`environmentfilter` and :func:`contextfilter`.
549
550Here a small example filter that breaks a text into HTML line breaks and
551paragraphs and marks the return value as safe HTML string if autoescaping is
552enabled::
553
554 import re
555 from jinja2 import environmentfilter, Markup, escape
556
557 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
558
559 @environmentfilter
560 def nl2br(environment, value):
561 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
562 for p in _paragraph_re.split(escape(value)))
563 if environment.autoescape:
564 result = Markup(result)
565 return result
566
567Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200568active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200569
570
571.. _writing-tests:
572
573Custom Tests
574------------
575
Armin Ronachera5d8f552008-09-11 20:46:34 +0200576Tests work like filters just that there is no way for a test to get access
Armin Ronacher7259c762008-04-30 13:03:59 +0200577to the environment or context and that they can't be chained. The return
Armin Ronachera5d8f552008-09-11 20:46:34 +0200578value of a test should be `True` or `False`. The purpose of a test is to
Armin Ronacher7259c762008-04-30 13:03:59 +0200579give the template designers the possibility to perform type and conformability
580checks.
581
Armin Ronachera5d8f552008-09-11 20:46:34 +0200582Here a simple test that checks if a variable is a prime number::
Armin Ronacher7259c762008-04-30 13:03:59 +0200583
584 import math
585
586 def is_prime(n):
587 if n == 2:
588 return True
589 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
590 if n % i == 0:
591 return False
592 return True
593
594
595You can register it on the template environment by updating the
596:attr:`~Environment.tests` dict on the environment::
597
598 environment.tests['prime'] = is_prime
599
600A template designer can then use the test like this:
601
602.. sourcecode:: jinja
603
604 {% if 42 is prime %}
605 42 is a prime number
606 {% else %}
607 42 is not a prime number
608 {% endif %}
609
610
611.. _global-namespace:
612
613The Global Namespace
614--------------------
615
Armin Ronacher981cbf62008-05-13 09:12:27 +0200616Variables stored in the :attr:`Environment.globals` dict are special as they
617are available for imported templates too, even if they are imported without
618context. This is the place where you can put variables and functions
619that should be available all the time. Additionally :attr:`Template.globals`
620exist that are variables available to a specific template that are available
621to all :meth:`~Template.render` calls.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200622
623
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200624.. _low-level-api:
625
Armin Ronacher5411ce72008-05-25 11:36:22 +0200626Low Level API
627-------------
628
629The low level API exposes functionality that can be useful to understand some
630implementation details, debugging purposes or advanced :ref:`extension
Armin Ronacher61a5a242008-05-26 12:07:44 +0200631<jinja-extensions>` techniques. Unless you know exactly what you are doing we
632don't recommend using any of those.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200633
634.. automethod:: Environment.lex
635
636.. automethod:: Environment.parse
637
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200638.. automethod:: Environment.preprocess
639
Armin Ronacher5411ce72008-05-25 11:36:22 +0200640.. automethod:: Template.new_context
641
642.. method:: Template.root_render_func(context)
643
644 This is the low level render function. It's passed a :class:`Context`
645 that has to be created by :meth:`new_context` of the same template or
646 a compatible template. This render function is generated by the
647 compiler from the template code and returns a generator that yields
648 unicode strings.
649
650 If an exception in the template code happens the template engine will
651 not rewrite the exception but pass through the original one. As a
652 matter of fact this function should only be called from within a
653 :meth:`render` / :meth:`generate` / :meth:`stream` call.
654
655.. attribute:: Template.blocks
656
657 A dict of block render functions. Each of these functions works exactly
658 like the :meth:`root_render_func` with the same limitations.
659
660.. attribute:: Template.is_up_to_date
661
662 This attribute is `False` if there is a newer version of the template
663 available, otherwise `True`.
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200664
665.. admonition:: Note
666
Armin Ronacher58f351d2008-05-28 21:30:14 +0200667 The low-level API is fragile. Future Jinja2 versions will try not to
668 change it in a backwards incompatible way but modifications in the Jinja2
669 core may shine through. For example if Jinja2 introduces a new AST node
670 in later versions that may be returned by :meth:`~Environment.parse`.
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200671
672The Meta API
673------------
674
675.. versionadded:: 2.2
676
677The meta API returns some information about abstract syntax trees that
678could help applications to implement more advanced template concepts. All
679the functions of the meta API operate on an abstract syntax tree as
680returned by the :meth:`Environment.parse` method.
681
682.. autofunction:: jinja2.meta.find_undeclared_variables
683
684.. autofunction:: jinja2.meta.find_referenced_templates