Skip to content
This repository
Newer
Older
100644 787 lines (529 sloc) 27.449 kb
3c8b7ade »
2008-04-28 first version of the jinja2 docs
1 API
2 ===
3
4 .. module:: jinja2
5 :synopsis: public Jinja2 API
6
7 This document describes the API to Jinja2 and not the template language. It
8 will be most useful as reference to those implementing the template interface
9 to the application and not those who are creating Jinja2 templates.
10
11 Basics
12 ------
13
14 Jinja2 uses a central object called the template :class:`Environment`.
15 Instances of this class are used to store the configuration, global objects
16 and are used to load templates from the file system or other locations.
0aa0f58a »
2009-03-18 Applied documentation patches by Clemens Hermann.
17 Even if you are creating templates from strings by using the constructor of
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
18 :class:`Template` class, an environment is created automatically for you,
19 albeit a shared one.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
20
21 Most applications will create one :class:`Environment` object on application
22 initialization and use that to load templates. In some cases it's however
23 useful to have multiple environments side by side, if different configurations
24 are in use.
25
26 The simplest way to configure Jinja2 to load templates for your application
27 looks roughly like this::
28
29 from jinja2 import Environment, PackageLoader
30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
31
32 This will create a template environment with the default settings and a
33 loader that looks up the templates in the `templates` folder inside the
34 `yourapplication` python package. Different loaders are available
35 and you can also write your own if you want to load templates from a
36 database or other resources.
37
38 To 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
43 To render it with some variables, just call the :meth:`render` method::
44
45 print template.render(the='variables', go='here')
46
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
47 Using a template loader rather then passing strings to :class:`Template`
48 or :meth:`Environment.from_string` has multiple advantages. Besides being
49 a lot easier to use it also enables template inheritance.
50
3c8b7ade »
2008-04-28 first version of the jinja2 docs
51
f3c35c42 »
2008-05-23 end of line sequence is no configurable
52 Unicode
53 -------
54
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
55 Jinja2 is using Unicode internally which means that you have to pass Unicode
f3c35c42 »
2008-05-23 end of line sequence is no configurable
56 objects to the render function or bytestrings that only consist of ASCII
57 characters. Additionally newlines are normalized to one end of line
58 sequence which is per default UNIX style (``\n``).
59
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
60 Python 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
62 called `basestring`. Unfortunately the default is `str` which should not
63 be used to store text based information unless only ASCII characters are
0aa0f58a »
2009-03-18 Applied documentation patches by Clemens Hermann.
64 used. With Python 2.6 it is possible to make `unicode` the default on a per
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
65 module level and with Python 3 it will be the default.
66
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
67 To explicitly use a Unicode string you have to prefix the string literal
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
68 with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
69 store the string as Unicode by decoding the string with the character
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
70 encoding from the current Python module. If no encoding is specified this
71 defaults to 'ASCII' which means that you can't use any non ASCII identifier.
72
73 To set a better module encoding add the following comment to the first or
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
74 second line of the Python module using the Unicode literal::
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
75
76 # -*- coding: utf-8 -*-
77
78 We recommend utf-8 as Encoding for Python modules and templates as it's
79 possible to represent every Unicode character in utf-8 and because it's
80 backwards compatible to ASCII. For Jinja2 the default encoding of templates
81 is assumed to be utf-8.
82
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
83 It is not possible to use Jinja2 to process non-Unicode data. The reason
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
84 for this is that Jinja2 uses Unicode already on the language level. For
85 example Jinja2 treats the non-breaking space as valid whitespace inside
86 expressions which requires knowledge of the encoding or operating on an
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
87 Unicode string.
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
88
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
89 For more details about Unicode in Python have a look at the excellent
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
90 `Unicode documentation`_.
91
58f351da »
2008-05-28 data files are optional now
92 Another important thing is how Jinja2 is handling string literals in
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
93 templates. A naive implementation would be using Unicode strings for
58f351da »
2008-05-28 data files are optional now
94 all string literals but it turned out in the past that this is problematic
95 as some libraries are typechecking against `str` explicitly. For example
656d5e7c »
2010-02-09 Some tiny documentation fixes (unicode -> Unicode)
96 `datetime.strftime` does not accept Unicode arguments. To not break it
58f351da »
2008-05-28 data files are optional now
97 completely Jinja2 is returning `str` for strings that fit into ASCII and
98 for everything else `unicode`:
99
100 >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
101 >>> m.a
102 'foo'
103 >>> m.b
104 u'f\xf6\xf6'
105
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
106
107 .. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
f3c35c42 »
2008-05-23 end of line sequence is no configurable
108
3c8b7ade »
2008-04-28 first version of the jinja2 docs
109 High Level API
110 --------------
111
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
112 The high-level API is the API you will use in the application to load and
113 render Jinja2 templates. The :ref:`low-level-api` on the other side is only
114 useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
115 <jinja-extensions>`.
116
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
117 .. autoclass:: Environment([options])
31bbd9e3 »
2010-01-14 include tags are now able to select between multiple templates
118 :members: from_string, get_template, select_template,
119 get_or_select_template, join_path, extend, compile_expression
3c8b7ade »
2008-04-28 first version of the jinja2 docs
120
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
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
138 loaded it's safe to add new filters or remove old. For custom filters
d1ff858a »
2008-05-11 Backed out changeset 6afb554797b6, which added unicode identifier sup…
139 see :ref:`writing-filters`. For valid filter names have a look at
140 :ref:`identifier-naming`.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
141
142 .. attribute:: tests
143
ad48a2e5 » Lukas Meuser
2008-05-01 Fixed typos in documentation
144 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
d1ff858a »
2008-05-11 Backed out changeset 6afb554797b6, which added unicode identifier sup…
146 see :ref:`writing-tests`. For valid test names have a look at
147 :ref:`identifier-naming`.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
148
149 .. attribute:: globals
150
151 A dict of global variables. These variables are always available
981cbf6e »
2008-05-13 removed unused imports
152 in a template. As long as no template was loaded it's safe
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
153 to modify this dict. For more details see :ref:`global-namespace`.
d1ff858a »
2008-05-11 Backed out changeset 6afb554797b6, which added unicode identifier sup…
154 For valid object names have a look at :ref:`identifier-naming`.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
155
ed98cac7 »
2008-05-07 some documentation updates
156 .. automethod:: overlay([options])
157
58f351da »
2008-05-28 data files are optional now
158 .. method:: undefined([hint, obj, name, exc])
3c8b7ade »
2008-04-28 first version of the jinja2 docs
159
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
160 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
0aa0f58a »
2009-03-18 Applied documentation patches by Clemens Hermann.
165 message will be generated from `obj` and `name` automatically. The exception
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
166 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
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
194 :members: module, make_module
3c8b7ade »
2008-04-28 first version of the jinja2 docs
195
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
196 .. attribute:: globals
197
ed98cac7 »
2008-05-07 some documentation updates
198 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.
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
201
202 .. attribute:: name
203
ed98cac7 »
2008-05-07 some documentation updates
204 The loading name of the template. If the template was loaded from a
205 string this is `None`.
206
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
207 .. 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
ed98cac7 »
2008-05-07 some documentation updates
212 .. automethod:: render([context])
213
214 .. automethod:: generate([context])
215
216 .. automethod:: stream([context])
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
217
3c8b7ade »
2008-04-28 first version of the jinja2 docs
218
6df604ec »
2008-05-23 more unittests and updated documentation for extensions. Fixed bug in…
219 .. autoclass:: jinja2.environment.TemplateStream()
74b51061 »
2008-06-17 Added `TemplateStream.dump`.
220 :members: disable_buffering, enable_buffering, dump
3c8b7ade »
2008-04-28 first version of the jinja2 docs
221
222
1da23d19 »
2010-04-05 autoescape no longer is a plain boolean value but can also be a function
223 Autoescaping
224 ------------
225
226 .. versionadded:: 2.4
227
228 As of Jinja 2.4 the preferred way to do autoescaping is to enable the
229 :ref:`autoescape-extension` and to configure a sensible default for
230 autoescaping. This makes it possible to enable and disable autoescaping
231 on a per-template basis (HTML versus text for instance).
232
233 Here a recommended setup that enables autoescaping for templates ending
234 in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default
235 for all other extensions::
236
237 def guess_autoescape(template_name):
238 if template_name is None or '.' not in template_name:
239 return False
240 ext = template_name.rsplit('.', 1)[1]
241 return ext in ('html', 'htm', 'xml')
242
243 env = Environment(autoescape=guess_autoescape,
244 loader=PackageLoader('mypackage'),
245 extensions=['jinja2.ext.autoescape'])
246
247 When implementing a guessing autoescape function, make sure you also
248 accept `None` as valid template name. This will be passed when generating
249 templates from strings.
250
251 Inside the templates the behaviour can be temporarily changed by using
252 the `autoescape` block (see :ref:`autoescape-overrides`).
253
254
d1ff858a »
2008-05-11 Backed out changeset 6afb554797b6, which added unicode identifier sup…
255 .. _identifier-naming:
256
257 Notes on Identifiers
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
258 --------------------
d1ff858a »
2008-05-11 Backed out changeset 6afb554797b6, which added unicode identifier sup…
259
260 Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
261 match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
262 are currently not allowed. This limitation will probably go away as soon as
263 unicode identifiers are fully specified for Python 3.
264
265 Filters and tests are looked up in separate namespaces and have slightly
266 modified identifier syntax. Filters and tests may contain dots to group
267 filters and tests by topic. For example it's perfectly valid to add a
268 function into the filter dict and call it `to.unicode`. The regular
269 expression for filter and test identifiers is
270 ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
271
272
3c8b7ade »
2008-04-28 first version of the jinja2 docs
273 Undefined Types
274 ---------------
275
276 These classes can be used as undefined types. The :class:`Environment`
277 constructor takes an `undefined` parameter that can be one of those classes
278 or a custom subclass of :class:`Undefined`. Whenever the template engine is
279 unable to look up a name or access an attribute one of those objects is
280 created and returned. Some operations on undefined values are then allowed,
281 others fail.
282
283 The closest to regular Python behavior is the `StrictUndefined` which
284 disallows all operations beside testing if it's an undefined object.
285
a816bf48 »
2008-09-17 Improved bbcache and documented it.
286 .. autoclass:: jinja2.Undefined()
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
287
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
288 .. attribute:: _undefined_hint
289
290 Either `None` or an unicode string with the error message for
291 the undefined object.
292
293 .. attribute:: _undefined_obj
294
295 Either `None` or the owner object that caused the undefined object
296 to be created (for example because an attribute does not exist).
297
298 .. attribute:: _undefined_name
299
300 The name for the undefined variable / attribute or just `None`
301 if no such information exists.
302
303 .. attribute:: _undefined_exception
304
305 The exception that the undefined object wants to raise. This
306 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
307
308 .. method:: _fail_with_undefined_error(\*args, \**kwargs)
309
310 When called with any arguments this method raises
311 :attr:`_undefined_exception` with an error message generated
312 from the undefined hints stored on the undefined object.
313
a816bf48 »
2008-09-17 Improved bbcache and documented it.
314 .. autoclass:: jinja2.DebugUndefined()
3c8b7ade »
2008-04-28 first version of the jinja2 docs
315
a816bf48 »
2008-09-17 Improved bbcache and documented it.
316 .. autoclass:: jinja2.StrictUndefined()
3c8b7ade »
2008-04-28 first version of the jinja2 docs
317
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
318 Undefined objects are created by calling :attr:`undefined`.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
319
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
320 .. admonition:: Implementation
321
322 :class:`Undefined` objects are implemented by overriding the special
323 `__underscore__` methods. For example the default :class:`Undefined`
324 class implements `__unicode__` in a way that it returns an empty
325 string, however `__int__` and others still fail with an exception. To
326 allow conversion to int by returning ``0`` you can implement your own::
327
328 class NullUndefined(Undefined):
329 def __int__(self):
330 return 0
331 def __float__(self):
332 return 0.0
333
334 To disallow a method, just override it and raise
58f351da »
2008-05-28 data files are optional now
335 :attr:`~Undefined._undefined_exception`. Because this is a very common
336 idom in undefined objects there is the helper method
337 :meth:`~Undefined._fail_with_undefined_error` that does the error raising
338 automatically. Here a class that works like the regular :class:`Undefined`
339 but chokes on iteration::
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
340
341 class NonIterableUndefined(Undefined):
342 __iter__ = Undefined._fail_with_undefined_error
343
3c8b7ade »
2008-04-28 first version of the jinja2 docs
344
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
345 The Context
346 -----------
347
6df604ec »
2008-05-23 more unittests and updated documentation for extensions. Fixed bug in…
348 .. autoclass:: jinja2.runtime.Context()
f35e2815 »
2008-05-06 some documentation improvements, jinja escapes " and ' now, both into…
349 :members: resolve, get_exported, get_all
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
350
351 .. attribute:: parent
352
353 A dict of read only, global variables the template looks up. These
19cf9c20 »
2008-05-01 small performance improvements
354 can either come from another :class:`Context`, from the
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
355 :attr:`Environment.globals` or :attr:`Template.globals` or points
356 to a dict created by combining the globals with the variables
357 passed to the render function. It must not be altered.
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
358
359 .. attribute:: vars
360
361 The template local variables. This list contains environment and
362 context functions from the :attr:`parent` scope as well as local
363 modifications and exported variables from the template. The template
364 will modify this dict during template evaluation but filters and
365 context functions are not allowed to modify it.
366
367 .. attribute:: environment
368
369 The environment that loaded the template.
370
371 .. attribute:: exported_vars
372
373 This set contains all the names the template exports. The values for
374 the names are in the :attr:`vars` dict. In order to get a copy of the
375 exported variables as dict, :meth:`get_exported` can be used.
376
377 .. attribute:: name
378
379 The load name of the template owning this context.
380
381 .. attribute:: blocks
382
383 A dict with the current mapping of blocks in the template. The keys
384 in this dict are the names of the blocks, and the values a list of
385 blocks registered. The last item in each list is the current active
386 block (latest in the inheritance chain).
387
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
388 .. attribute:: eval_ctx
389
390 The current :ref:`eval-context`.
391
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
392 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
393
394
395 .. admonition:: Implementation
396
397 Context is immutable for the same reason Python's frame locals are
398 immutable inside functions. Both Jinja2 and Python are not using the
399 context / frame locals as data storage for variables but only as primary
400 data source.
401
402 When a template accesses a variable the template does not define, Jinja2
403 looks up the variable in the context, after that the variable is treated
404 as if it was defined in the template.
405
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
406
5cdc1ac3 »
2008-05-07 documentation update
407 .. _loaders:
408
3c8b7ade »
2008-04-28 first version of the jinja2 docs
409 Loaders
410 -------
411
412 Loaders are responsible for loading templates from a resource such as the
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
413 file system. The environment will keep the compiled modules in memory like
414 Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
415 size by default and templates are automatically reloaded.
cda43df1 »
2008-05-03 updated filters: wordwraps uses the wordwrap module and urlize marks …
416 All loaders are subclasses of :class:`BaseLoader`. If you want to create your
417 own loader, subclass :class:`BaseLoader` and override `get_source`.
418
a816bf48 »
2008-09-17 Improved bbcache and documented it.
419 .. autoclass:: jinja2.BaseLoader
cda43df1 »
2008-05-03 updated filters: wordwraps uses the wordwrap module and urlize marks …
420 :members: get_source, load
421
422 Here a list of the builtin loaders Jinja2 provides:
3c8b7ade »
2008-04-28 first version of the jinja2 docs
423
a816bf48 »
2008-09-17 Improved bbcache and documented it.
424 .. autoclass:: jinja2.FileSystemLoader
3c8b7ade »
2008-04-28 first version of the jinja2 docs
425
a816bf48 »
2008-09-17 Improved bbcache and documented it.
426 .. autoclass:: jinja2.PackageLoader
3c8b7ade »
2008-04-28 first version of the jinja2 docs
427
a816bf48 »
2008-09-17 Improved bbcache and documented it.
428 .. autoclass:: jinja2.DictLoader
3c8b7ade »
2008-04-28 first version of the jinja2 docs
429
a816bf48 »
2008-09-17 Improved bbcache and documented it.
430 .. autoclass:: jinja2.FunctionLoader
3c8b7ade »
2008-04-28 first version of the jinja2 docs
431
a816bf48 »
2008-09-17 Improved bbcache and documented it.
432 .. autoclass:: jinja2.PrefixLoader
3c8b7ade »
2008-04-28 first version of the jinja2 docs
433
a816bf48 »
2008-09-17 Improved bbcache and documented it.
434 .. autoclass:: jinja2.ChoiceLoader
435
436
437 .. _bytecode-cache:
438
439 Bytecode Cache
440 --------------
441
442 Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
443 it possible to store the generated bytecode on the file system or a different
444 location to avoid parsing the templates on first use.
445
446 This is especially useful if you have a web application that is initialized on
447 the first request and Jinja compiles many templates at once which slows down
448 the application.
449
450 To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.
451
452 .. autoclass:: jinja2.BytecodeCache
453 :members: load_bytecode, dump_bytecode, clear
454
455 .. autoclass:: jinja2.bccache.Bucket
456 :members: write_bytecode, load_bytecode, bytecode_from_string,
457 bytecode_to_string, reset
458
459 .. attribute:: environment
460
461 The :class:`Environment` that created the bucket.
462
463 .. attribute:: key
464
465 The unique cache key for this bucket
466
467 .. attribute:: code
468
469 The bytecode if it's loaded, otherwise `None`.
470
471
472 Builtin bytecode caches:
473
474 .. autoclass:: jinja2.FileSystemBytecodeCache
3c8b7ade »
2008-04-28 first version of the jinja2 docs
475
aa1d17d6 »
2008-09-18 Fixed bytecode cache and added support for memcached (tests still mis…
476 .. autoclass:: jinja2.MemcachedBytecodeCache
477
3c8b7ade »
2008-04-28 first version of the jinja2 docs
478
479 Utilities
480 ---------
481
482 These helper functions and classes are useful if you add custom filters or
483 functions to a Jinja2 environment.
484
a816bf48 »
2008-09-17 Improved bbcache and documented it.
485 .. autofunction:: jinja2.environmentfilter
3c8b7ade »
2008-04-28 first version of the jinja2 docs
486
a816bf48 »
2008-09-17 Improved bbcache and documented it.
487 .. autofunction:: jinja2.contextfilter
3c8b7ade »
2008-04-28 first version of the jinja2 docs
488
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
489 .. autofunction:: jinja2.evalcontextfilter
490
a816bf48 »
2008-09-17 Improved bbcache and documented it.
491 .. autofunction:: jinja2.environmentfunction
3c8b7ade »
2008-04-28 first version of the jinja2 docs
492
a816bf48 »
2008-09-17 Improved bbcache and documented it.
493 .. autofunction:: jinja2.contextfunction
3c8b7ade »
2008-04-28 first version of the jinja2 docs
494
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
495 .. autofunction:: jinja2.evalcontextfunction
496
3c8b7ade »
2008-04-28 first version of the jinja2 docs
497 .. function:: escape(s)
498
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
499 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
500 to HTML-safe sequences. Use this if you need to display text that might
501 contain such characters in HTML. This function will not escaped objects
502 that do have an HTML representation such as already escaped data.
503
504 The return value is a :class:`Markup` string.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
505
a816bf48 »
2008-09-17 Improved bbcache and documented it.
506 .. autofunction:: jinja2.clear_caches
187bde1a »
2008-05-01 added cache_clear function
507
a816bf48 »
2008-09-17 Improved bbcache and documented it.
508 .. autofunction:: jinja2.is_undefined
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
509
a816bf48 »
2008-09-17 Improved bbcache and documented it.
510 .. autoclass:: jinja2.Markup([string])
58f351da »
2008-05-28 data files are optional now
511 :members: escape, unescape, striptags
512
513 .. admonition:: Note
514
515 The Jinja2 :class:`Markup` class is compatible with at least Pylons and
516 Genshi. It's expected that more template engines and framework will pick
517 up the `__html__` concept soon.
3c8b7ade »
2008-04-28 first version of the jinja2 docs
518
519
520 Exceptions
521 ----------
522
a816bf48 »
2008-09-17 Improved bbcache and documented it.
523 .. autoexception:: jinja2.TemplateError
3c8b7ade »
2008-04-28 first version of the jinja2 docs
524
a816bf48 »
2008-09-17 Improved bbcache and documented it.
525 .. autoexception:: jinja2.UndefinedError
3c8b7ade »
2008-04-28 first version of the jinja2 docs
526
a816bf48 »
2008-09-17 Improved bbcache and documented it.
527 .. autoexception:: jinja2.TemplateNotFound
3c8b7ade »
2008-04-28 first version of the jinja2 docs
528
31bbd9e3 »
2010-01-14 include tags are now able to select between multiple templates
529 .. autoexception:: jinja2.TemplatesNotFound
530
a816bf48 »
2008-09-17 Improved bbcache and documented it.
531 .. autoexception:: jinja2.TemplateSyntaxError
3c8b7ade »
2008-04-28 first version of the jinja2 docs
532
f3c35c42 »
2008-05-23 end of line sequence is no configurable
533 .. attribute:: message
534
535 The error message as utf-8 bytestring.
536
537 .. attribute:: lineno
538
539 The line number where the error occurred
540
541 .. attribute:: name
542
543 The load name for the template as unicode string.
544
545 .. attribute:: filename
546
547 The filename that loaded the template as bytestring in the encoding
548 of the file system (most likely utf-8 or mbcs on Windows systems).
549
550 The reason why the filename and error message are bytestrings and not
551 unicode strings is that Python 2.x is not using unicode for exceptions
552 and tracebacks as well as the compiler. This will change with Python 3.
553
a816bf48 »
2008-09-17 Improved bbcache and documented it.
554 .. autoexception:: jinja2.TemplateAssertionError
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
555
556
557 .. _writing-filters:
558
559 Custom Filters
560 --------------
561
562 Custom filters are just regular Python functions that take the left side of
563 the filter as first argument and the the arguments passed to the filter as
564 extra arguments or keyword arguments.
565
566 For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
567 called with ``myfilter(42, 23)``. Here for example a simple filter that can
568 be applied to datetime objects to format them::
569
570 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
571 return value.strftime(format)
572
573 You can register it on the template environment by updating the
574 :attr:`~Environment.filters` dict on the environment::
575
576 environment.filters['datetimeformat'] = datetimeformat
577
578 Inside the template it can then be used as follows:
579
580 .. sourcecode:: jinja
581
582 written on: {{ article.pub_date|datetimeformat }}
583 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
584
585 Filters can also be passed the current template context or environment. This
0aa0f58a »
2009-03-18 Applied documentation patches by Clemens Hermann.
586 is useful if a filter wants to return an undefined value or check the current
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
587 :attr:`~Environment.autoescape` setting. For this purpose two decorators
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
588 exist: :func:`environmentfilter`, :func:`contextfilter` and
589 :func:`evalcontextfilter`.
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
590
591 Here a small example filter that breaks a text into HTML line breaks and
592 paragraphs and marks the return value as safe HTML string if autoescaping is
593 enabled::
594
595 import re
596 from jinja2 import environmentfilter, Markup, escape
597
598 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
599
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
600 @evalcontextfilter
601 def nl2br(eval_ctx, value):
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
602 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
603 for p in _paragraph_re.split(escape(value)))
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
604 if eval_ctx.autoescape:
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
605 result = Markup(result)
606 return result
607
608 Context filters work the same just that the first argument is the current
19cf9c20 »
2008-05-01 small performance improvements
609 active :class:`Context` rather then the environment.
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
610
611
fe150f3c »
2010-03-15 Documented autoescaping behavior and eval contexts.
612 .. _eval-context:
613
614 Evaluation Context
615 ------------------
616
617 The evaluation context (short eval context or eval ctx) is a new object
618 introducted in Jinja 2.4 that makes it possible to activate and deactivate
619 compiled features at runtime.
620
621 Currently it is only used to enable and disable the automatic escaping but
622 can be used for extensions as well.
623
624 In previous Jinja versions filters and functions were marked as
625 environment callables in order to check for the autoescape status from the
626 environment. In new versions it's encouraged to check the setting from the
627 evaluation context instead.
628
629 Previous versions::
630
631 @environmentfilter
632 def filter(env, value):
633 result = do_something(value)
634 if env.autoescape:
635 result = Markup(result)
636 return result
637
638 In new versions you can either use a :func:`contextfilter` and access the
639 evaluation context from the actual context, or use a
640 :func:`evalcontextfilter` which directly passes the evaluation context to
641 the function::
642
643 @contextfilter
644 def filter(context, value):
645 result = do_something(value)
646 if context.eval_ctx.autoescape:
647 result = Markup(result)
648 return result
649
650 @evalcontextfilter
651 def filter(eval_ctx, value):
652 result = do_something(value)
653 if eval_ctx.autoescape:
654 result = Markup(result)
655 return result
656
657 The evaluation context must not be modified at runtime. Modifications
658 must only happen with a :class:`nodes.EvalContextModifier` and
659 :class:`nodes.ScopedEvalContextModifier` from an extension, not on the
660 eval context object itself.
661
76ae15ea »
2010-03-15 Hopefully fixed EvalContext documentation.
662 .. autoclass:: jinja2.nodes.EvalContext
30fda270 »
2010-03-15 More documentation updates.
663
664 .. attribute:: autoescape
665
666 `True` or `False` depending on if autoescaping is active or not.
667
668 .. attribute:: volatile
669
670 `True` if the compiler cannot evaluate some expressions at compile
671 time. At runtime this should always be `False`.
672
673
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
674 .. _writing-tests:
675
676 Custom Tests
677 ------------
678
a5d8f55e »
2008-09-11 filter -> test in the tests section (i feel so embarrassed).
679 Tests work like filters just that there is no way for a test to get access
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
680 to the environment or context and that they can't be chained. The return
a5d8f55e »
2008-09-11 filter -> test in the tests section (i feel so embarrassed).
681 value of a test should be `True` or `False`. The purpose of a test is to
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
682 give the template designers the possibility to perform type and conformability
683 checks.
684
a5d8f55e »
2008-09-11 filter -> test in the tests section (i feel so embarrassed).
685 Here a simple test that checks if a variable is a prime number::
7259c766 »
2008-04-30 moved caching from loaders to environment and added environment overlays
686
687 import math
688
689 def is_prime(n):
690 if n == 2:
691 return True
692 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
693 if n % i == 0:
694 return False
695 return True
696
697
698 You can register it on the template environment by updating the
699 :attr:`~Environment.tests` dict on the environment::
700
701 environment.tests['prime'] = is_prime
702
703 A template designer can then use the test like this:
704
705 .. sourcecode:: jinja
706
707 {% if 42 is prime %}
708 42 is a prime number
709 {% else %}
710 42 is not a prime number
711 {% endif %}
712
713
714 .. _global-namespace:
715
716 The Global Namespace
717 --------------------
718
981cbf6e »
2008-05-13 removed unused imports
719 Variables stored in the :attr:`Environment.globals` dict are special as they
720 are available for imported templates too, even if they are imported without
721 context. This is the place where you can put variables and functions
722 that should be available all the time. Additionally :attr:`Template.globals`
723 exist that are variables available to a specific template that are available
724 to all :meth:`~Template.render` calls.
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
725
726
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
727 .. _low-level-api:
728
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
729 Low Level API
730 -------------
731
732 The low level API exposes functionality that can be useful to understand some
733 implementation details, debugging purposes or advanced :ref:`extension
61a5a24a »
2008-05-26 fixed a bug in error reporting and some small documentation updates
734 <jinja-extensions>` techniques. Unless you know exactly what you are doing we
735 don't recommend using any of those.
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
736
737 .. automethod:: Environment.lex
738
739 .. automethod:: Environment.parse
740
9ad96e7a »
2008-06-13 added support for token stream filtering and preprocessing.
741 .. automethod:: Environment.preprocess
742
5411ce72 »
2008-05-25 even more tests, fixed severe bug with autoescaping.
743 .. automethod:: Template.new_context
744
745 .. method:: Template.root_render_func(context)
746
747 This is the low level render function. It's passed a :class:`Context`
748 that has to be created by :meth:`new_context` of the same template or
749 a compatible template. This render function is generated by the
750 compiler from the template code and returns a generator that yields
751 unicode strings.
752
753 If an exception in the template code happens the template engine will
754 not rewrite the exception but pass through the original one. As a
755 matter of fact this function should only be called from within a
756 :meth:`render` / :meth:`generate` / :meth:`stream` call.
757
758 .. attribute:: Template.blocks
759
760 A dict of block render functions. Each of these functions works exactly
761 like the :meth:`root_render_func` with the same limitations.
762
763 .. attribute:: Template.is_up_to_date
764
765 This attribute is `False` if there is a newer version of the template
766 available, otherwise `True`.
9bb7e477 »
2008-05-28 some more documentation updates and minor code cleanups. Additionally…
767
768 .. admonition:: Note
769
58f351da »
2008-05-28 data files are optional now
770 The low-level API is fragile. Future Jinja2 versions will try not to
771 change it in a backwards incompatible way but modifications in the Jinja2
772 core may shine through. For example if Jinja2 introduces a new AST node
773 in later versions that may be returned by :meth:`~Environment.parse`.
63cf9b89 »
2009-07-26 Added the `meta` module.
774
775 The Meta API
776 ------------
777
778 .. versionadded:: 2.2
779
780 The meta API returns some information about abstract syntax trees that
781 could help applications to implement more advanced template concepts. All
782 the functions of the meta API operate on an abstract syntax tree as
783 returned by the :meth:`Environment.parse` method.
784
785 .. autofunction:: jinja2.meta.find_undeclared_variables
786
787 .. autofunction:: jinja2.meta.find_referenced_templates
Something went wrong with that request. Please try again.