Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 402 lines (261 sloc) 13.306 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.
17 Even if you are creating templates from string by using the constructor of
18 :class:`Template` class, an environment is created automatically for you.
19
20 Most applications will create one :class:`Environment` object on application
21 initialization and use that to load templates. In some cases it's however
22 useful to have multiple environments side by side, if different configurations
23 are in use.
24
25 The simplest way to configure Jinja2 to load templates for your application
26 looks roughly like this::
27
28 from jinja2 import Environment, PackageLoader
29 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
30
31 This will create a template environment with the default settings and a
32 loader that looks up the templates in the `templates` folder inside the
33 `yourapplication` python package. Different loaders are available
34 and you can also write your own if you want to load templates from a
35 database or other resources.
36
37 To 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
42 To render it with some variables, just call the :meth:`render` method::
43
44 print template.render(the='variables', go='here')
45
46
f3c35c4 @mitsuhiko end of line sequence is no configurable
authored
47 Unicode
48 -------
49
50 Jinja2 is using unicode internally which means that you have to pass unicode
51 objects to the render function or bytestrings that only consist of ASCII
52 characters. Additionally newlines are normalized to one end of line
53 sequence which is per default UNIX style (``\n``).
54
55
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
56 High Level API
57 --------------
58
ed98cac @mitsuhiko some documentation updates
authored
59 .. autoclass:: jinja2.environment.Environment([options])
762079c @mitsuhiko more updates on the extension API
authored
60 :members: from_string, get_template, join_path, parse, lex, extend
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
61
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
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
79 loaded it's safe to add new filters or remove old. For custom filters
d1ff858 @mitsuhiko Backed out changeset 6afb554797b6, which added unicode identifier suppor...
authored
80 see :ref:`writing-filters`. For valid filter names have a look at
81 :ref:`identifier-naming`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
82
83 .. attribute:: tests
84
ad48a2e Fixed typos in documentation
Lukas Meuser authored
85 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
d1ff858 @mitsuhiko Backed out changeset 6afb554797b6, which added unicode identifier suppor...
authored
87 see :ref:`writing-tests`. For valid test names have a look at
88 :ref:`identifier-naming`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
89
90 .. attribute:: globals
91
92 A dict of global variables. These variables are always available
981cbf6 @mitsuhiko removed unused imports
authored
93 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
94 to modify this dict. For more details see :ref:`global-namespace`.
d1ff858 @mitsuhiko Backed out changeset 6afb554797b6, which added unicode identifier suppor...
authored
95 For valid object names have a look at :ref:`identifier-naming`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
96
ed98cac @mitsuhiko some documentation updates
authored
97 .. automethod:: overlay([options])
98
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
99
100 .. autoclass:: jinja2.Template
ed98cac @mitsuhiko some documentation updates
authored
101 :members: make_module, module, new_context
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
102
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
103 .. attribute:: globals
104
ed98cac @mitsuhiko some documentation updates
authored
105 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.
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
108
109 .. attribute:: name
110
ed98cac @mitsuhiko some documentation updates
authored
111 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])
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
119
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
120
6df604e @mitsuhiko more unittests and updated documentation for extensions. Fixed bug in o...
authored
121 .. autoclass:: jinja2.environment.TemplateStream()
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
122 :members: disable_buffering, enable_buffering
123
124
d1ff858 @mitsuhiko Backed out changeset 6afb554797b6, which added unicode identifier suppor...
authored
125 .. _identifier-naming:
126
127 Notes on Identifiers
128 ~~~~~~~~~~~~~~~~~~~~
129
130 Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
131 match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
132 are currently not allowed. This limitation will probably go away as soon as
133 unicode identifiers are fully specified for Python 3.
134
135 Filters and tests are looked up in separate namespaces and have slightly
136 modified identifier syntax. Filters and tests may contain dots to group
137 filters and tests by topic. For example it's perfectly valid to add a
138 function into the filter dict and call it `to.unicode`. The regular
139 expression for filter and test identifiers is
140 ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
141
142
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
143 Undefined Types
144 ---------------
145
146 These classes can be used as undefined types. The :class:`Environment`
147 constructor takes an `undefined` parameter that can be one of those classes
148 or a custom subclass of :class:`Undefined`. Whenever the template engine is
149 unable to look up a name or access an attribute one of those objects is
150 created and returned. Some operations on undefined values are then allowed,
151 others fail.
152
153 The closest to regular Python behavior is the `StrictUndefined` which
154 disallows 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
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
163 The Context
164 -----------
165
6df604e @mitsuhiko more unittests and updated documentation for extensions. Fixed bug in o...
authored
166 .. autoclass:: jinja2.runtime.Context()
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
167 :members: resolve, get_exported, get_all
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
168
169 .. attribute:: parent
170
171 A dict of read only, global variables the template looks up. These
19cf9c2 @mitsuhiko small performance improvements
authored
172 can either come from another :class:`Context`, from the
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
173 :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
5cdc1ac @mitsuhiko documentation update
authored
206 .. _loaders:
207
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
208 Loaders
209 -------
210
211 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
212 file system. The environment will keep the compiled modules in memory like
213 Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
214 size by default and templates are automatically reloaded.
cda43df @mitsuhiko updated filters: wordwraps uses the wordwrap module and urlize marks the...
authored
215 All loaders are subclasses of :class:`BaseLoader`. If you want to create your
216 own loader, subclass :class:`BaseLoader` and override `get_source`.
217
218 .. autoclass:: jinja2.loaders.BaseLoader
219 :members: get_source, load
220
221 Here a list of the builtin loaders Jinja2 provides:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
222
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
235
236 Utilities
237 ---------
238
239 These helper functions and classes are useful if you add custom filters or
240 functions 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
187bde1 @mitsuhiko added cache_clear function
authored
257 .. autofunction:: jinja2.utils.clear_caches
258
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
259 .. autoclass:: jinja2.utils.Markup
260
261
262 Exceptions
263 ----------
264
5cdc1ac @mitsuhiko documentation update
authored
265 .. autoexception:: jinja2.exceptions.TemplateError
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
266
5cdc1ac @mitsuhiko documentation update
authored
267 .. autoexception:: jinja2.exceptions.UndefinedError
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
268
5cdc1ac @mitsuhiko documentation update
authored
269 .. autoexception:: jinja2.exceptions.TemplateNotFound
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
270
5cdc1ac @mitsuhiko documentation update
authored
271 .. autoexception:: jinja2.exceptions.TemplateSyntaxError
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
272
f3c35c4 @mitsuhiko end of line sequence is no configurable
authored
273 .. 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
5cdc1ac @mitsuhiko documentation update
authored
294 .. autoexception:: jinja2.exceptions.TemplateAssertionError
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
295
296
297 .. _writing-filters:
298
299 Custom Filters
300 --------------
301
302 Custom filters are just regular Python functions that take the left side of
303 the filter as first argument and the the arguments passed to the filter as
304 extra arguments or keyword arguments.
305
306 For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
307 called with ``myfilter(42, 23)``. Here for example a simple filter that can
308 be applied to datetime objects to format them::
309
310 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
311 return value.strftime(format)
312
313 You 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
318 Inside 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
325 Filters can also be passed the current template context or environment. This
326 is useful if a filters wants to return an undefined value or check the current
327 :attr:`~Environment.autoescape` setting. For this purpose two decorators
328 exist: :func:`environmentfilter` and :func:`contextfilter`.
329
330 Here a small example filter that breaks a text into HTML line breaks and
331 paragraphs and marks the return value as safe HTML string if autoescaping is
332 enabled::
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
347 Context filters work the same just that the first argument is the current
19cf9c2 @mitsuhiko small performance improvements
authored
348 active :class:`Context` rather then the environment.
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
349
350
351 .. _writing-tests:
352
353 Custom Tests
354 ------------
355
356 Tests work like filters just that there is no way for a filter to get access
357 to the environment or context and that they can't be chained. The return
358 value of a filter should be `True` or `False`. The purpose of a filter is to
359 give the template designers the possibility to perform type and conformability
360 checks.
361
362 Here 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
375 You 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
380 A 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
393 The Global Namespace
394 --------------------
395
981cbf6 @mitsuhiko removed unused imports
authored
396 Variables stored in the :attr:`Environment.globals` dict are special as they
397 are available for imported templates too, even if they are imported without
398 context. This is the place where you can put variables and functions
399 that should be available all the time. Additionally :attr:`Template.globals`
400 exist that are variables available to a specific template that are available
401 to all :meth:`~Template.render` calls.
Something went wrong with that request. Please try again.