blob: 5a131ed3b62aa69ef6ea898d4efd03efead04b19 [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
47High Level API
48--------------
49
Armin Ronachered98cac2008-05-07 08:42:11 +020050.. autoclass:: jinja2.environment.Environment([options])
Armin Ronacher762079c2008-05-08 23:57:56 +020051 :members: from_string, get_template, join_path, parse, lex, extend
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020052
53 .. attribute:: shared
54
55 If a template was created by using the :class:`Template` constructor
56 an environment is created automatically. These environments are
57 created as shared environments which means that multiple templates
58 may have the same anonymous environment. For all shared environments
59 this attribute is `True`, else `False`.
60
61 .. attribute:: sandboxed
62
63 If the environment is sandboxed this attribute is `True`. For the
64 sandbox mode have a look at the documentation for the
65 :class:`~jinja2.sandbox.SandboxedEnvironment`.
66
67 .. attribute:: filters
68
69 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +020070 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +020071 see :ref:`writing-filters`. For valid filter names have a look at
72 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020073
74 .. attribute:: tests
75
Lukas Meuserad48a2e2008-05-01 18:19:57 +020076 A dict of test functions for this environment. As long as no
77 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +020078 see :ref:`writing-tests`. For valid test names have a look at
79 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020080
81 .. attribute:: globals
82
83 A dict of global variables. These variables are always available
84 in a template and (if the optimizer is enabled) may not be
Lukas Meuserad48a2e2008-05-01 18:19:57 +020085 overridden by templates. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +020086 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +020087 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020088
Armin Ronachered98cac2008-05-07 08:42:11 +020089 .. automethod:: overlay([options])
90
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020091
92.. autoclass:: jinja2.Template
Armin Ronachered98cac2008-05-07 08:42:11 +020093 :members: make_module, module, new_context
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020094
Armin Ronacher7259c762008-04-30 13:03:59 +020095 .. attribute:: globals
96
Armin Ronachered98cac2008-05-07 08:42:11 +020097 The dict with the globals of that template. It's unsafe to modify
98 this dict as it may be shared with other templates or the environment
99 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200100
101 .. attribute:: name
102
Armin Ronachered98cac2008-05-07 08:42:11 +0200103 The loading name of the template. If the template was loaded from a
104 string this is `None`.
105
106 .. automethod:: render([context])
107
108 .. automethod:: generate([context])
109
110 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200111
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200112
113.. autoclass:: jinja2.environment.TemplateStream
114 :members: disable_buffering, enable_buffering
115
116
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200117.. _identifier-naming:
118
119Notes on Identifiers
120~~~~~~~~~~~~~~~~~~~~
121
122Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
123match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
124are currently not allowed. This limitation will probably go away as soon as
125unicode identifiers are fully specified for Python 3.
126
127Filters and tests are looked up in separate namespaces and have slightly
128modified identifier syntax. Filters and tests may contain dots to group
129filters and tests by topic. For example it's perfectly valid to add a
130function into the filter dict and call it `to.unicode`. The regular
131expression for filter and test identifiers is
132``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
133
134
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200135Undefined Types
136---------------
137
138These classes can be used as undefined types. The :class:`Environment`
139constructor takes an `undefined` parameter that can be one of those classes
140or a custom subclass of :class:`Undefined`. Whenever the template engine is
141unable to look up a name or access an attribute one of those objects is
142created and returned. Some operations on undefined values are then allowed,
143others fail.
144
145The closest to regular Python behavior is the `StrictUndefined` which
146disallows all operations beside testing if it's an undefined object.
147
148.. autoclass:: jinja2.runtime.Undefined
149
150.. autoclass:: jinja2.runtime.DebugUndefined
151
152.. autoclass:: jinja2.runtime.StrictUndefined
153
154
Armin Ronacher7259c762008-04-30 13:03:59 +0200155The Context
156-----------
157
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200158.. autoclass:: jinja2.runtime.Context
Armin Ronacherf35e2812008-05-06 16:04:10 +0200159 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200160
161 .. attribute:: parent
162
163 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200164 can either come from another :class:`Context`, from the
Armin Ronacher7259c762008-04-30 13:03:59 +0200165 :attr:`Environment.globals` or :attr:`Template.globals`. It must not
166 be altered.
167
168 .. attribute:: vars
169
170 The template local variables. This list contains environment and
171 context functions from the :attr:`parent` scope as well as local
172 modifications and exported variables from the template. The template
173 will modify this dict during template evaluation but filters and
174 context functions are not allowed to modify it.
175
176 .. attribute:: environment
177
178 The environment that loaded the template.
179
180 .. attribute:: exported_vars
181
182 This set contains all the names the template exports. The values for
183 the names are in the :attr:`vars` dict. In order to get a copy of the
184 exported variables as dict, :meth:`get_exported` can be used.
185
186 .. attribute:: name
187
188 The load name of the template owning this context.
189
190 .. attribute:: blocks
191
192 A dict with the current mapping of blocks in the template. The keys
193 in this dict are the names of the blocks, and the values a list of
194 blocks registered. The last item in each list is the current active
195 block (latest in the inheritance chain).
196
197
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200198.. _loaders:
199
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200200Loaders
201-------
202
203Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200204file system. The environment will keep the compiled modules in memory like
205Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
206size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200207All loaders are subclasses of :class:`BaseLoader`. If you want to create your
208
209own loader, subclass :class:`BaseLoader` and override `get_source`.
210
211.. autoclass:: jinja2.loaders.BaseLoader
212 :members: get_source, load
213
214Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200215
216.. autoclass:: jinja2.loaders.FileSystemLoader
217
218.. autoclass:: jinja2.loaders.PackageLoader
219
220.. autoclass:: jinja2.loaders.DictLoader
221
222.. autoclass:: jinja2.loaders.FunctionLoader
223
224.. autoclass:: jinja2.loaders.PrefixLoader
225
226.. autoclass:: jinja2.loaders.ChoiceLoader
227
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200228
229Utilities
230---------
231
232These helper functions and classes are useful if you add custom filters or
233functions to a Jinja2 environment.
234
235.. autofunction:: jinja2.filters.environmentfilter
236
237.. autofunction:: jinja2.filters.contextfilter
238
239.. autofunction:: jinja2.utils.environmentfunction
240
241.. autofunction:: jinja2.utils.contextfunction
242
243.. function:: escape(s)
244
245 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
246 Use this if you need to display text that might contain such characters
247 in HTML. This function will not escaped objects that do have an HTML
248 representation such as already escaped data.
249
Armin Ronacher187bde12008-05-01 18:19:16 +0200250.. autofunction:: jinja2.utils.clear_caches
251
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200252.. autoclass:: jinja2.utils.Markup
253
254
255Exceptions
256----------
257
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200258.. autoexception:: jinja2.exceptions.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200259
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200260.. autoexception:: jinja2.exceptions.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200261
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200262.. autoexception:: jinja2.exceptions.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200263
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200264.. autoexception:: jinja2.exceptions.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200265
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200266.. autoexception:: jinja2.exceptions.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200267
268
269.. _writing-filters:
270
271Custom Filters
272--------------
273
274Custom filters are just regular Python functions that take the left side of
275the filter as first argument and the the arguments passed to the filter as
276extra arguments or keyword arguments.
277
278For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
279called with ``myfilter(42, 23)``. Here for example a simple filter that can
280be applied to datetime objects to format them::
281
282 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
283 return value.strftime(format)
284
285You can register it on the template environment by updating the
286:attr:`~Environment.filters` dict on the environment::
287
288 environment.filters['datetimeformat'] = datetimeformat
289
290Inside the template it can then be used as follows:
291
292.. sourcecode:: jinja
293
294 written on: {{ article.pub_date|datetimeformat }}
295 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
296
297Filters can also be passed the current template context or environment. This
298is useful if a filters wants to return an undefined value or check the current
299:attr:`~Environment.autoescape` setting. For this purpose two decorators
300exist: :func:`environmentfilter` and :func:`contextfilter`.
301
302Here a small example filter that breaks a text into HTML line breaks and
303paragraphs and marks the return value as safe HTML string if autoescaping is
304enabled::
305
306 import re
307 from jinja2 import environmentfilter, Markup, escape
308
309 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
310
311 @environmentfilter
312 def nl2br(environment, value):
313 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
314 for p in _paragraph_re.split(escape(value)))
315 if environment.autoescape:
316 result = Markup(result)
317 return result
318
319Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200320active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200321
322
323.. _writing-tests:
324
325Custom Tests
326------------
327
328Tests work like filters just that there is no way for a filter to get access
329to the environment or context and that they can't be chained. The return
330value of a filter should be `True` or `False`. The purpose of a filter is to
331give the template designers the possibility to perform type and conformability
332checks.
333
334Here a simple filter that checks if a variable is a prime number::
335
336 import math
337
338 def is_prime(n):
339 if n == 2:
340 return True
341 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
342 if n % i == 0:
343 return False
344 return True
345
346
347You can register it on the template environment by updating the
348:attr:`~Environment.tests` dict on the environment::
349
350 environment.tests['prime'] = is_prime
351
352A template designer can then use the test like this:
353
354.. sourcecode:: jinja
355
356 {% if 42 is prime %}
357 42 is a prime number
358 {% else %}
359 42 is not a prime number
360 {% endif %}
361
362
363.. _global-namespace:
364
365The Global Namespace
366--------------------
367
368Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`
369dicts are special as they are available for imported templates too and will be
370used by the optimizer in future releases to evaluates parts of the template at
371compile time. This is the place where you can put variables and functions
372that should be available all the time.