Skip to content

HTTPS clone URL

Subversion checkout URL

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