blob: 95064b562181cc203773909599a1423cc9f82620 [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 Ronachered98cac2008-05-07 08:42:11 +020059.. autoclass:: jinja2.environment.Environment([options])
Armin Ronacher762079c2008-05-08 23:57:56 +020060 :members: from_string, get_template, join_path, parse, lex, 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 Ronacher3c8b7ad2008-04-28 13:52:21 +020099
100.. autoclass:: jinja2.Template
Armin Ronachered98cac2008-05-07 08:42:11 +0200101 :members: make_module, module, new_context
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200102
Armin Ronacher7259c762008-04-30 13:03:59 +0200103 .. attribute:: globals
104
Armin Ronachered98cac2008-05-07 08:42:11 +0200105 The dict with the globals of that template. It's unsafe to modify
106 this dict as it may be shared with other templates or the environment
107 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200108
109 .. attribute:: name
110
Armin Ronachered98cac2008-05-07 08:42:11 +0200111 The loading name of the template. If the template was loaded from a
112 string this is `None`.
113
114 .. automethod:: render([context])
115
116 .. automethod:: generate([context])
117
118 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200119
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200120
Armin Ronacher6df604e2008-05-23 22:18:38 +0200121.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200122 :members: disable_buffering, enable_buffering
123
124
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200125.. _identifier-naming:
126
127Notes on Identifiers
128~~~~~~~~~~~~~~~~~~~~
129
130Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
131match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
132are currently not allowed. This limitation will probably go away as soon as
133unicode identifiers are fully specified for Python 3.
134
135Filters and tests are looked up in separate namespaces and have slightly
136modified identifier syntax. Filters and tests may contain dots to group
137filters and tests by topic. For example it's perfectly valid to add a
138function into the filter dict and call it `to.unicode`. The regular
139expression for filter and test identifiers is
140``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
141
142
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200143Undefined Types
144---------------
145
146These classes can be used as undefined types. The :class:`Environment`
147constructor takes an `undefined` parameter that can be one of those classes
148or a custom subclass of :class:`Undefined`. Whenever the template engine is
149unable to look up a name or access an attribute one of those objects is
150created and returned. Some operations on undefined values are then allowed,
151others fail.
152
153The closest to regular Python behavior is the `StrictUndefined` which
154disallows all operations beside testing if it's an undefined object.
155
156.. autoclass:: jinja2.runtime.Undefined
157
158.. autoclass:: jinja2.runtime.DebugUndefined
159
160.. autoclass:: jinja2.runtime.StrictUndefined
161
162
Armin Ronacher7259c762008-04-30 13:03:59 +0200163The Context
164-----------
165
Armin Ronacher6df604e2008-05-23 22:18:38 +0200166.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200167 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200168
169 .. attribute:: parent
170
171 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200172 can either come from another :class:`Context`, from the
Armin Ronacher7259c762008-04-30 13:03:59 +0200173 :attr:`Environment.globals` or :attr:`Template.globals`. It must not
174 be altered.
175
176 .. attribute:: vars
177
178 The template local variables. This list contains environment and
179 context functions from the :attr:`parent` scope as well as local
180 modifications and exported variables from the template. The template
181 will modify this dict during template evaluation but filters and
182 context functions are not allowed to modify it.
183
184 .. attribute:: environment
185
186 The environment that loaded the template.
187
188 .. attribute:: exported_vars
189
190 This set contains all the names the template exports. The values for
191 the names are in the :attr:`vars` dict. In order to get a copy of the
192 exported variables as dict, :meth:`get_exported` can be used.
193
194 .. attribute:: name
195
196 The load name of the template owning this context.
197
198 .. attribute:: blocks
199
200 A dict with the current mapping of blocks in the template. The keys
201 in this dict are the names of the blocks, and the values a list of
202 blocks registered. The last item in each list is the current active
203 block (latest in the inheritance chain).
204
205
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200206.. _loaders:
207
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200208Loaders
209-------
210
211Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200212file system. The environment will keep the compiled modules in memory like
213Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
214size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200215All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200216own loader, subclass :class:`BaseLoader` and override `get_source`.
217
218.. autoclass:: jinja2.loaders.BaseLoader
219 :members: get_source, load
220
221Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200222
223.. autoclass:: jinja2.loaders.FileSystemLoader
224
225.. autoclass:: jinja2.loaders.PackageLoader
226
227.. autoclass:: jinja2.loaders.DictLoader
228
229.. autoclass:: jinja2.loaders.FunctionLoader
230
231.. autoclass:: jinja2.loaders.PrefixLoader
232
233.. autoclass:: jinja2.loaders.ChoiceLoader
234
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200235
236Utilities
237---------
238
239These helper functions and classes are useful if you add custom filters or
240functions to a Jinja2 environment.
241
242.. autofunction:: jinja2.filters.environmentfilter
243
244.. autofunction:: jinja2.filters.contextfilter
245
246.. autofunction:: jinja2.utils.environmentfunction
247
248.. autofunction:: jinja2.utils.contextfunction
249
250.. function:: escape(s)
251
252 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
253 Use this if you need to display text that might contain such characters
254 in HTML. This function will not escaped objects that do have an HTML
255 representation such as already escaped data.
256
Armin Ronacher187bde12008-05-01 18:19:16 +0200257.. autofunction:: jinja2.utils.clear_caches
258
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200259.. autoclass:: jinja2.utils.Markup
260
261
262Exceptions
263----------
264
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200265.. autoexception:: jinja2.exceptions.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200266
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200267.. autoexception:: jinja2.exceptions.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200268
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200269.. autoexception:: jinja2.exceptions.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200270
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200271.. autoexception:: jinja2.exceptions.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200272
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200273 .. attribute:: message
274
275 The error message as utf-8 bytestring.
276
277 .. attribute:: lineno
278
279 The line number where the error occurred
280
281 .. attribute:: name
282
283 The load name for the template as unicode string.
284
285 .. attribute:: filename
286
287 The filename that loaded the template as bytestring in the encoding
288 of the file system (most likely utf-8 or mbcs on Windows systems).
289
290 The reason why the filename and error message are bytestrings and not
291 unicode strings is that Python 2.x is not using unicode for exceptions
292 and tracebacks as well as the compiler. This will change with Python 3.
293
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200294.. autoexception:: jinja2.exceptions.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200295
296
297.. _writing-filters:
298
299Custom Filters
300--------------
301
302Custom filters are just regular Python functions that take the left side of
303the filter as first argument and the the arguments passed to the filter as
304extra arguments or keyword arguments.
305
306For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
307called with ``myfilter(42, 23)``. Here for example a simple filter that can
308be applied to datetime objects to format them::
309
310 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
311 return value.strftime(format)
312
313You can register it on the template environment by updating the
314:attr:`~Environment.filters` dict on the environment::
315
316 environment.filters['datetimeformat'] = datetimeformat
317
318Inside the template it can then be used as follows:
319
320.. sourcecode:: jinja
321
322 written on: {{ article.pub_date|datetimeformat }}
323 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
324
325Filters can also be passed the current template context or environment. This
326is useful if a filters wants to return an undefined value or check the current
327:attr:`~Environment.autoescape` setting. For this purpose two decorators
328exist: :func:`environmentfilter` and :func:`contextfilter`.
329
330Here a small example filter that breaks a text into HTML line breaks and
331paragraphs and marks the return value as safe HTML string if autoescaping is
332enabled::
333
334 import re
335 from jinja2 import environmentfilter, Markup, escape
336
337 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
338
339 @environmentfilter
340 def nl2br(environment, value):
341 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
342 for p in _paragraph_re.split(escape(value)))
343 if environment.autoescape:
344 result = Markup(result)
345 return result
346
347Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200348active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200349
350
351.. _writing-tests:
352
353Custom Tests
354------------
355
356Tests work like filters just that there is no way for a filter to get access
357to the environment or context and that they can't be chained. The return
358value of a filter should be `True` or `False`. The purpose of a filter is to
359give the template designers the possibility to perform type and conformability
360checks.
361
362Here a simple filter that checks if a variable is a prime number::
363
364 import math
365
366 def is_prime(n):
367 if n == 2:
368 return True
369 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
370 if n % i == 0:
371 return False
372 return True
373
374
375You can register it on the template environment by updating the
376:attr:`~Environment.tests` dict on the environment::
377
378 environment.tests['prime'] = is_prime
379
380A template designer can then use the test like this:
381
382.. sourcecode:: jinja
383
384 {% if 42 is prime %}
385 42 is a prime number
386 {% else %}
387 42 is not a prime number
388 {% endif %}
389
390
391.. _global-namespace:
392
393The Global Namespace
394--------------------
395
Armin Ronacher981cbf62008-05-13 09:12:27 +0200396Variables stored in the :attr:`Environment.globals` dict are special as they
397are available for imported templates too, even if they are imported without
398context. This is the place where you can put variables and functions
399that should be available all the time. Additionally :attr:`Template.globals`
400exist that are variables available to a specific template that are available
401to all :meth:`~Template.render` calls.