blob: cba97ea231b7dbc5ec85299107bd59923007c84e [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
18:class:`Template` class, an environment is created automatically for you.
19
20Most applications will create one :class:`Environment` object on application
21initialization and use that to load templates. In some cases it's however
22useful to have multiple environments side by side, if different configurations
23are in use.
24
25The simplest way to configure Jinja2 to load templates for your application
26looks roughly like this::
27
28 from jinja2 import Environment, PackageLoader
29 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
30
31This will create a template environment with the default settings and a
32loader that looks up the templates in the `templates` folder inside the
33`yourapplication` python package. Different loaders are available
34and you can also write your own if you want to load templates from a
35database or other resources.
36
37To load a template from this environment you just have to call the
38:meth:`get_template` method which then returns the loaded :class:`Template`::
39
40 template = env.get_template('mytemplate.html')
41
42To render it with some variables, just call the :meth:`render` method::
43
44 print template.render(the='variables', go='here')
45
46
Armin Ronacherf3c35c42008-05-23 23:18:14 +020047Unicode
48-------
49
50Jinja2 is using unicode internally which means that you have to pass unicode
51objects to the render function or bytestrings that only consist of ASCII
52characters. Additionally newlines are normalized to one end of line
53sequence which is per default UNIX style (``\n``).
54
55
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020056High Level API
57--------------
58
Armin Ronacher5411ce72008-05-25 11:36:22 +020059.. autoclass:: Environment([options])
60 :members: from_string, get_template, join_path, extend
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020061
62 .. attribute:: shared
63
64 If a template was created by using the :class:`Template` constructor
65 an environment is created automatically. These environments are
66 created as shared environments which means that multiple templates
67 may have the same anonymous environment. For all shared environments
68 this attribute is `True`, else `False`.
69
70 .. attribute:: sandboxed
71
72 If the environment is sandboxed this attribute is `True`. For the
73 sandbox mode have a look at the documentation for the
74 :class:`~jinja2.sandbox.SandboxedEnvironment`.
75
76 .. attribute:: filters
77
78 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +020079 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +020080 see :ref:`writing-filters`. For valid filter names have a look at
81 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020082
83 .. attribute:: tests
84
Lukas Meuserad48a2e2008-05-01 18:19:57 +020085 A dict of test functions for this environment. As long as no
86 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +020087 see :ref:`writing-tests`. For valid test names have a look at
88 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020089
90 .. attribute:: globals
91
92 A dict of global variables. These variables are always available
Armin Ronacher981cbf62008-05-13 09:12:27 +020093 in a template. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +020094 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +020095 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020096
Armin Ronachered98cac2008-05-07 08:42:11 +020097 .. automethod:: overlay([options])
98
Armin Ronacher5411ce72008-05-25 11:36:22 +020099 .. method:: undefined([hint,] [obj,] name[, exc])
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200100
Armin Ronacher5411ce72008-05-25 11:36:22 +0200101 Creates a new :class:`Undefined` object for `name`. This is useful
102 for filters or functions that may return undefined objects for
103 some operations. All parameters except of `hint` should be provided
104 as keyword parameters for better readability. The `hint` is used as
105 error message for the exception if provided, otherwise the error
106 message generated from `obj` and `name` automatically. The exception
107 provided as `exc` is raised if something with the generated undefined
108 object is done that the undefined object does not allow. The default
109 exception is :exc:`UndefinedError`. If a `hint` is provided the
110 `name` may be ommited.
111
112 The most common way to create an undefined object is by providing
113 a name only::
114
115 return environment.undefined(name='some_name')
116
117 This means that the name `some_name` is not defined. If the name
118 was from an attribute of an object it makes sense to tell the
119 undefined object the holder object to improve the error message::
120
121 if not hasattr(obj, 'attr'):
122 return environment.undefined(obj=obj, name='attr')
123
124 For a more complex example you can provide a hint. For example
125 the :func:`first` filter creates an undefined object that way::
126
127 return environment.undefined('no first item, sequence was empty')
128
129 If it the `name` or `obj` is known (for example because an attribute
130 was accessed) it shold be passed to the undefined object, even if
131 a custom `hint` is provided. This gives undefined objects the
132 possibility to enhance the error message.
133
134.. autoclass:: Template
Armin Ronachered98cac2008-05-07 08:42:11 +0200135 :members: make_module, module, new_context
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200136
Armin Ronacher7259c762008-04-30 13:03:59 +0200137 .. attribute:: globals
138
Armin Ronachered98cac2008-05-07 08:42:11 +0200139 The dict with the globals of that template. It's unsafe to modify
140 this dict as it may be shared with other templates or the environment
141 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200142
143 .. attribute:: name
144
Armin Ronachered98cac2008-05-07 08:42:11 +0200145 The loading name of the template. If the template was loaded from a
146 string this is `None`.
147
Armin Ronacher5411ce72008-05-25 11:36:22 +0200148 .. attribute:: filename
149
150 The filename of the template on the file system if it was loaded from
151 there. Otherwise this is `None`.
152
Armin Ronachered98cac2008-05-07 08:42:11 +0200153 .. automethod:: render([context])
154
155 .. automethod:: generate([context])
156
157 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200158
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200159
Armin Ronacher6df604e2008-05-23 22:18:38 +0200160.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200161 :members: disable_buffering, enable_buffering
162
163
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200164.. _identifier-naming:
165
166Notes on Identifiers
Armin Ronacher5411ce72008-05-25 11:36:22 +0200167--------------------
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200168
169Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
170match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
171are currently not allowed. This limitation will probably go away as soon as
172unicode identifiers are fully specified for Python 3.
173
174Filters and tests are looked up in separate namespaces and have slightly
175modified identifier syntax. Filters and tests may contain dots to group
176filters and tests by topic. For example it's perfectly valid to add a
177function into the filter dict and call it `to.unicode`. The regular
178expression for filter and test identifiers is
179``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
180
181
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200182Undefined Types
183---------------
184
185These classes can be used as undefined types. The :class:`Environment`
186constructor takes an `undefined` parameter that can be one of those classes
187or a custom subclass of :class:`Undefined`. Whenever the template engine is
188unable to look up a name or access an attribute one of those objects is
189created and returned. Some operations on undefined values are then allowed,
190others fail.
191
192The closest to regular Python behavior is the `StrictUndefined` which
193disallows all operations beside testing if it's an undefined object.
194
Armin Ronacher5411ce72008-05-25 11:36:22 +0200195.. autoclass:: jinja2.runtime.Undefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200196
Armin Ronacher5411ce72008-05-25 11:36:22 +0200197.. autoclass:: jinja2.runtime.DebugUndefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200198
Armin Ronacher5411ce72008-05-25 11:36:22 +0200199.. autoclass:: jinja2.runtime.StrictUndefined()
200
201Undefined objects are created by calling :attr:`undefined`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200202
203
Armin Ronacher7259c762008-04-30 13:03:59 +0200204The Context
205-----------
206
Armin Ronacher6df604e2008-05-23 22:18:38 +0200207.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200208 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200209
210 .. attribute:: parent
211
212 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200213 can either come from another :class:`Context`, from the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200214 :attr:`Environment.globals` or :attr:`Template.globals` or points
215 to a dict created by combining the globals with the variables
216 passed to the render function. It must not be altered.
Armin Ronacher7259c762008-04-30 13:03:59 +0200217
218 .. attribute:: vars
219
220 The template local variables. This list contains environment and
221 context functions from the :attr:`parent` scope as well as local
222 modifications and exported variables from the template. The template
223 will modify this dict during template evaluation but filters and
224 context functions are not allowed to modify it.
225
226 .. attribute:: environment
227
228 The environment that loaded the template.
229
230 .. attribute:: exported_vars
231
232 This set contains all the names the template exports. The values for
233 the names are in the :attr:`vars` dict. In order to get a copy of the
234 exported variables as dict, :meth:`get_exported` can be used.
235
236 .. attribute:: name
237
238 The load name of the template owning this context.
239
240 .. attribute:: blocks
241
242 A dict with the current mapping of blocks in the template. The keys
243 in this dict are the names of the blocks, and the values a list of
244 blocks registered. The last item in each list is the current active
245 block (latest in the inheritance chain).
246
247
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200248.. _loaders:
249
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200250Loaders
251-------
252
253Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200254file system. The environment will keep the compiled modules in memory like
255Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
256size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200257All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200258own loader, subclass :class:`BaseLoader` and override `get_source`.
259
260.. autoclass:: jinja2.loaders.BaseLoader
261 :members: get_source, load
262
263Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200264
265.. autoclass:: jinja2.loaders.FileSystemLoader
266
267.. autoclass:: jinja2.loaders.PackageLoader
268
269.. autoclass:: jinja2.loaders.DictLoader
270
271.. autoclass:: jinja2.loaders.FunctionLoader
272
273.. autoclass:: jinja2.loaders.PrefixLoader
274
275.. autoclass:: jinja2.loaders.ChoiceLoader
276
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200277
278Utilities
279---------
280
281These helper functions and classes are useful if you add custom filters or
282functions to a Jinja2 environment.
283
284.. autofunction:: jinja2.filters.environmentfilter
285
286.. autofunction:: jinja2.filters.contextfilter
287
288.. autofunction:: jinja2.utils.environmentfunction
289
290.. autofunction:: jinja2.utils.contextfunction
291
292.. function:: escape(s)
293
294 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
295 Use this if you need to display text that might contain such characters
296 in HTML. This function will not escaped objects that do have an HTML
297 representation such as already escaped data.
298
Armin Ronacher187bde12008-05-01 18:19:16 +0200299.. autofunction:: jinja2.utils.clear_caches
300
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200301.. autoclass:: jinja2.utils.Markup
302
303
304Exceptions
305----------
306
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200307.. autoexception:: jinja2.exceptions.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200308
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200309.. autoexception:: jinja2.exceptions.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200310
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200311.. autoexception:: jinja2.exceptions.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200312
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200313.. autoexception:: jinja2.exceptions.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200314
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200315 .. attribute:: message
316
317 The error message as utf-8 bytestring.
318
319 .. attribute:: lineno
320
321 The line number where the error occurred
322
323 .. attribute:: name
324
325 The load name for the template as unicode string.
326
327 .. attribute:: filename
328
329 The filename that loaded the template as bytestring in the encoding
330 of the file system (most likely utf-8 or mbcs on Windows systems).
331
332 The reason why the filename and error message are bytestrings and not
333 unicode strings is that Python 2.x is not using unicode for exceptions
334 and tracebacks as well as the compiler. This will change with Python 3.
335
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200336.. autoexception:: jinja2.exceptions.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200337
338
339.. _writing-filters:
340
341Custom Filters
342--------------
343
344Custom filters are just regular Python functions that take the left side of
345the filter as first argument and the the arguments passed to the filter as
346extra arguments or keyword arguments.
347
348For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
349called with ``myfilter(42, 23)``. Here for example a simple filter that can
350be applied to datetime objects to format them::
351
352 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
353 return value.strftime(format)
354
355You can register it on the template environment by updating the
356:attr:`~Environment.filters` dict on the environment::
357
358 environment.filters['datetimeformat'] = datetimeformat
359
360Inside the template it can then be used as follows:
361
362.. sourcecode:: jinja
363
364 written on: {{ article.pub_date|datetimeformat }}
365 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
366
367Filters can also be passed the current template context or environment. This
368is useful if a filters wants to return an undefined value or check the current
369:attr:`~Environment.autoescape` setting. For this purpose two decorators
370exist: :func:`environmentfilter` and :func:`contextfilter`.
371
372Here a small example filter that breaks a text into HTML line breaks and
373paragraphs and marks the return value as safe HTML string if autoescaping is
374enabled::
375
376 import re
377 from jinja2 import environmentfilter, Markup, escape
378
379 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
380
381 @environmentfilter
382 def nl2br(environment, value):
383 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
384 for p in _paragraph_re.split(escape(value)))
385 if environment.autoescape:
386 result = Markup(result)
387 return result
388
389Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200390active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200391
392
393.. _writing-tests:
394
395Custom Tests
396------------
397
398Tests work like filters just that there is no way for a filter to get access
399to the environment or context and that they can't be chained. The return
400value of a filter should be `True` or `False`. The purpose of a filter is to
401give the template designers the possibility to perform type and conformability
402checks.
403
404Here a simple filter that checks if a variable is a prime number::
405
406 import math
407
408 def is_prime(n):
409 if n == 2:
410 return True
411 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
412 if n % i == 0:
413 return False
414 return True
415
416
417You can register it on the template environment by updating the
418:attr:`~Environment.tests` dict on the environment::
419
420 environment.tests['prime'] = is_prime
421
422A template designer can then use the test like this:
423
424.. sourcecode:: jinja
425
426 {% if 42 is prime %}
427 42 is a prime number
428 {% else %}
429 42 is not a prime number
430 {% endif %}
431
432
433.. _global-namespace:
434
435The Global Namespace
436--------------------
437
Armin Ronacher981cbf62008-05-13 09:12:27 +0200438Variables stored in the :attr:`Environment.globals` dict are special as they
439are available for imported templates too, even if they are imported without
440context. This is the place where you can put variables and functions
441that should be available all the time. Additionally :attr:`Template.globals`
442exist that are variables available to a specific template that are available
443to all :meth:`~Template.render` calls.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200444
445
446Low Level API
447-------------
448
449The low level API exposes functionality that can be useful to understand some
450implementation details, debugging purposes or advanced :ref:`extension
451<jinja-extensions>` techniques.
452
453.. automethod:: Environment.lex
454
455.. automethod:: Environment.parse
456
457.. automethod:: Template.new_context
458
459.. method:: Template.root_render_func(context)
460
461 This is the low level render function. It's passed a :class:`Context`
462 that has to be created by :meth:`new_context` of the same template or
463 a compatible template. This render function is generated by the
464 compiler from the template code and returns a generator that yields
465 unicode strings.
466
467 If an exception in the template code happens the template engine will
468 not rewrite the exception but pass through the original one. As a
469 matter of fact this function should only be called from within a
470 :meth:`render` / :meth:`generate` / :meth:`stream` call.
471
472.. attribute:: Template.blocks
473
474 A dict of block render functions. Each of these functions works exactly
475 like the :meth:`root_render_func` with the same limitations.
476
477.. attribute:: Template.is_up_to_date
478
479 This attribute is `False` if there is a newer version of the template
480 available, otherwise `True`.