blob: cc9e9d82a4da919775946b2fe5b88c9da6a0810b [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.
17Even if you are creating templates from string 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
64used. With Python 2.6 it is possible to my `unicode` the default on a per
65module 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
92
93.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
Armin Ronacherf3c35c42008-05-23 23:18:14 +020094
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020095High Level API
96--------------
97
Armin Ronacher5411ce72008-05-25 11:36:22 +020098.. autoclass:: Environment([options])
99 :members: from_string, get_template, join_path, extend
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200100
101 .. attribute:: shared
102
103 If a template was created by using the :class:`Template` constructor
104 an environment is created automatically. These environments are
105 created as shared environments which means that multiple templates
106 may have the same anonymous environment. For all shared environments
107 this attribute is `True`, else `False`.
108
109 .. attribute:: sandboxed
110
111 If the environment is sandboxed this attribute is `True`. For the
112 sandbox mode have a look at the documentation for the
113 :class:`~jinja2.sandbox.SandboxedEnvironment`.
114
115 .. attribute:: filters
116
117 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +0200118 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200119 see :ref:`writing-filters`. For valid filter names have a look at
120 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200121
122 .. attribute:: tests
123
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200124 A dict of test functions for this environment. As long as no
125 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200126 see :ref:`writing-tests`. For valid test names have a look at
127 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200128
129 .. attribute:: globals
130
131 A dict of global variables. These variables are always available
Armin Ronacher981cbf62008-05-13 09:12:27 +0200132 in a template. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +0200133 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200134 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200135
Armin Ronachered98cac2008-05-07 08:42:11 +0200136 .. automethod:: overlay([options])
137
Armin Ronacher5411ce72008-05-25 11:36:22 +0200138 .. method:: undefined([hint,] [obj,] name[, exc])
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200139
Armin Ronacher5411ce72008-05-25 11:36:22 +0200140 Creates a new :class:`Undefined` object for `name`. This is useful
141 for filters or functions that may return undefined objects for
142 some operations. All parameters except of `hint` should be provided
143 as keyword parameters for better readability. The `hint` is used as
144 error message for the exception if provided, otherwise the error
145 message generated from `obj` and `name` automatically. The exception
146 provided as `exc` is raised if something with the generated undefined
147 object is done that the undefined object does not allow. The default
148 exception is :exc:`UndefinedError`. If a `hint` is provided the
149 `name` may be ommited.
150
151 The most common way to create an undefined object is by providing
152 a name only::
153
154 return environment.undefined(name='some_name')
155
156 This means that the name `some_name` is not defined. If the name
157 was from an attribute of an object it makes sense to tell the
158 undefined object the holder object to improve the error message::
159
160 if not hasattr(obj, 'attr'):
161 return environment.undefined(obj=obj, name='attr')
162
163 For a more complex example you can provide a hint. For example
164 the :func:`first` filter creates an undefined object that way::
165
166 return environment.undefined('no first item, sequence was empty')
167
168 If it the `name` or `obj` is known (for example because an attribute
169 was accessed) it shold be passed to the undefined object, even if
170 a custom `hint` is provided. This gives undefined objects the
171 possibility to enhance the error message.
172
173.. autoclass:: Template
Armin Ronachered98cac2008-05-07 08:42:11 +0200174 :members: make_module, module, new_context
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200175
Armin Ronacher7259c762008-04-30 13:03:59 +0200176 .. attribute:: globals
177
Armin Ronachered98cac2008-05-07 08:42:11 +0200178 The dict with the globals of that template. It's unsafe to modify
179 this dict as it may be shared with other templates or the environment
180 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200181
182 .. attribute:: name
183
Armin Ronachered98cac2008-05-07 08:42:11 +0200184 The loading name of the template. If the template was loaded from a
185 string this is `None`.
186
Armin Ronacher5411ce72008-05-25 11:36:22 +0200187 .. attribute:: filename
188
189 The filename of the template on the file system if it was loaded from
190 there. Otherwise this is `None`.
191
Armin Ronachered98cac2008-05-07 08:42:11 +0200192 .. automethod:: render([context])
193
194 .. automethod:: generate([context])
195
196 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200197
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200198
Armin Ronacher6df604e2008-05-23 22:18:38 +0200199.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200200 :members: disable_buffering, enable_buffering
201
202
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200203.. _identifier-naming:
204
205Notes on Identifiers
Armin Ronacher5411ce72008-05-25 11:36:22 +0200206--------------------
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200207
208Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
209match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
210are currently not allowed. This limitation will probably go away as soon as
211unicode identifiers are fully specified for Python 3.
212
213Filters and tests are looked up in separate namespaces and have slightly
214modified identifier syntax. Filters and tests may contain dots to group
215filters and tests by topic. For example it's perfectly valid to add a
216function into the filter dict and call it `to.unicode`. The regular
217expression for filter and test identifiers is
218``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
219
220
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200221Undefined Types
222---------------
223
224These classes can be used as undefined types. The :class:`Environment`
225constructor takes an `undefined` parameter that can be one of those classes
226or a custom subclass of :class:`Undefined`. Whenever the template engine is
227unable to look up a name or access an attribute one of those objects is
228created and returned. Some operations on undefined values are then allowed,
229others fail.
230
231The closest to regular Python behavior is the `StrictUndefined` which
232disallows all operations beside testing if it's an undefined object.
233
Armin Ronacher5411ce72008-05-25 11:36:22 +0200234.. autoclass:: jinja2.runtime.Undefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200235
Armin Ronacher5411ce72008-05-25 11:36:22 +0200236.. autoclass:: jinja2.runtime.DebugUndefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200237
Armin Ronacher5411ce72008-05-25 11:36:22 +0200238.. autoclass:: jinja2.runtime.StrictUndefined()
239
240Undefined objects are created by calling :attr:`undefined`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200241
242
Armin Ronacher7259c762008-04-30 13:03:59 +0200243The Context
244-----------
245
Armin Ronacher6df604e2008-05-23 22:18:38 +0200246.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200247 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200248
249 .. attribute:: parent
250
251 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200252 can either come from another :class:`Context`, from the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200253 :attr:`Environment.globals` or :attr:`Template.globals` or points
254 to a dict created by combining the globals with the variables
255 passed to the render function. It must not be altered.
Armin Ronacher7259c762008-04-30 13:03:59 +0200256
257 .. attribute:: vars
258
259 The template local variables. This list contains environment and
260 context functions from the :attr:`parent` scope as well as local
261 modifications and exported variables from the template. The template
262 will modify this dict during template evaluation but filters and
263 context functions are not allowed to modify it.
264
265 .. attribute:: environment
266
267 The environment that loaded the template.
268
269 .. attribute:: exported_vars
270
271 This set contains all the names the template exports. The values for
272 the names are in the :attr:`vars` dict. In order to get a copy of the
273 exported variables as dict, :meth:`get_exported` can be used.
274
275 .. attribute:: name
276
277 The load name of the template owning this context.
278
279 .. attribute:: blocks
280
281 A dict with the current mapping of blocks in the template. The keys
282 in this dict are the names of the blocks, and the values a list of
283 blocks registered. The last item in each list is the current active
284 block (latest in the inheritance chain).
285
286
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200287.. _loaders:
288
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200289Loaders
290-------
291
292Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200293file system. The environment will keep the compiled modules in memory like
294Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
295size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200296All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200297own loader, subclass :class:`BaseLoader` and override `get_source`.
298
299.. autoclass:: jinja2.loaders.BaseLoader
300 :members: get_source, load
301
302Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200303
304.. autoclass:: jinja2.loaders.FileSystemLoader
305
306.. autoclass:: jinja2.loaders.PackageLoader
307
308.. autoclass:: jinja2.loaders.DictLoader
309
310.. autoclass:: jinja2.loaders.FunctionLoader
311
312.. autoclass:: jinja2.loaders.PrefixLoader
313
314.. autoclass:: jinja2.loaders.ChoiceLoader
315
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200316
317Utilities
318---------
319
320These helper functions and classes are useful if you add custom filters or
321functions to a Jinja2 environment.
322
323.. autofunction:: jinja2.filters.environmentfilter
324
325.. autofunction:: jinja2.filters.contextfilter
326
327.. autofunction:: jinja2.utils.environmentfunction
328
329.. autofunction:: jinja2.utils.contextfunction
330
331.. function:: escape(s)
332
333 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
334 Use this if you need to display text that might contain such characters
335 in HTML. This function will not escaped objects that do have an HTML
336 representation such as already escaped data.
337
Armin Ronacher187bde12008-05-01 18:19:16 +0200338.. autofunction:: jinja2.utils.clear_caches
339
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200340.. autoclass:: jinja2.utils.Markup
341
342
343Exceptions
344----------
345
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200346.. autoexception:: jinja2.exceptions.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200347
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200348.. autoexception:: jinja2.exceptions.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200349
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200350.. autoexception:: jinja2.exceptions.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200351
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200352.. autoexception:: jinja2.exceptions.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200353
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200354 .. attribute:: message
355
356 The error message as utf-8 bytestring.
357
358 .. attribute:: lineno
359
360 The line number where the error occurred
361
362 .. attribute:: name
363
364 The load name for the template as unicode string.
365
366 .. attribute:: filename
367
368 The filename that loaded the template as bytestring in the encoding
369 of the file system (most likely utf-8 or mbcs on Windows systems).
370
371 The reason why the filename and error message are bytestrings and not
372 unicode strings is that Python 2.x is not using unicode for exceptions
373 and tracebacks as well as the compiler. This will change with Python 3.
374
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200375.. autoexception:: jinja2.exceptions.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200376
377
378.. _writing-filters:
379
380Custom Filters
381--------------
382
383Custom filters are just regular Python functions that take the left side of
384the filter as first argument and the the arguments passed to the filter as
385extra arguments or keyword arguments.
386
387For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
388called with ``myfilter(42, 23)``. Here for example a simple filter that can
389be applied to datetime objects to format them::
390
391 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
392 return value.strftime(format)
393
394You can register it on the template environment by updating the
395:attr:`~Environment.filters` dict on the environment::
396
397 environment.filters['datetimeformat'] = datetimeformat
398
399Inside the template it can then be used as follows:
400
401.. sourcecode:: jinja
402
403 written on: {{ article.pub_date|datetimeformat }}
404 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
405
406Filters can also be passed the current template context or environment. This
407is useful if a filters wants to return an undefined value or check the current
408:attr:`~Environment.autoescape` setting. For this purpose two decorators
409exist: :func:`environmentfilter` and :func:`contextfilter`.
410
411Here a small example filter that breaks a text into HTML line breaks and
412paragraphs and marks the return value as safe HTML string if autoescaping is
413enabled::
414
415 import re
416 from jinja2 import environmentfilter, Markup, escape
417
418 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
419
420 @environmentfilter
421 def nl2br(environment, value):
422 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
423 for p in _paragraph_re.split(escape(value)))
424 if environment.autoescape:
425 result = Markup(result)
426 return result
427
428Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200429active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200430
431
432.. _writing-tests:
433
434Custom Tests
435------------
436
437Tests work like filters just that there is no way for a filter to get access
438to the environment or context and that they can't be chained. The return
439value of a filter should be `True` or `False`. The purpose of a filter is to
440give the template designers the possibility to perform type and conformability
441checks.
442
443Here a simple filter that checks if a variable is a prime number::
444
445 import math
446
447 def is_prime(n):
448 if n == 2:
449 return True
450 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
451 if n % i == 0:
452 return False
453 return True
454
455
456You can register it on the template environment by updating the
457:attr:`~Environment.tests` dict on the environment::
458
459 environment.tests['prime'] = is_prime
460
461A template designer can then use the test like this:
462
463.. sourcecode:: jinja
464
465 {% if 42 is prime %}
466 42 is a prime number
467 {% else %}
468 42 is not a prime number
469 {% endif %}
470
471
472.. _global-namespace:
473
474The Global Namespace
475--------------------
476
Armin Ronacher981cbf62008-05-13 09:12:27 +0200477Variables stored in the :attr:`Environment.globals` dict are special as they
478are available for imported templates too, even if they are imported without
479context. This is the place where you can put variables and functions
480that should be available all the time. Additionally :attr:`Template.globals`
481exist that are variables available to a specific template that are available
482to all :meth:`~Template.render` calls.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200483
484
485Low Level API
486-------------
487
488The low level API exposes functionality that can be useful to understand some
489implementation details, debugging purposes or advanced :ref:`extension
Armin Ronacher61a5a242008-05-26 12:07:44 +0200490<jinja-extensions>` techniques. Unless you know exactly what you are doing we
491don't recommend using any of those.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200492
493.. automethod:: Environment.lex
494
495.. automethod:: Environment.parse
496
497.. automethod:: Template.new_context
498
499.. method:: Template.root_render_func(context)
500
501 This is the low level render function. It's passed a :class:`Context`
502 that has to be created by :meth:`new_context` of the same template or
503 a compatible template. This render function is generated by the
504 compiler from the template code and returns a generator that yields
505 unicode strings.
506
507 If an exception in the template code happens the template engine will
508 not rewrite the exception but pass through the original one. As a
509 matter of fact this function should only be called from within a
510 :meth:`render` / :meth:`generate` / :meth:`stream` call.
511
512.. attribute:: Template.blocks
513
514 A dict of block render functions. Each of these functions works exactly
515 like the :meth:`root_render_func` with the same limitations.
516
517.. attribute:: Template.is_up_to_date
518
519 This attribute is `False` if there is a newer version of the template
520 available, otherwise `True`.