Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 339 lines (219 sloc) 10.951 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
47 High Level API
48 --------------
49
50 .. autoclass:: jinja2.environment.Environment
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
51 :members: from_string, get_template, join_path, overlay
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
52
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
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
70 loaded it's safe to add new filters or remove old. For custom filters
71 see :ref:`writing-filters`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
72
73 .. attribute:: tests
74
ad48a2e Fixed typos in documentation
Lukas Meuser authored
75 A dict of test functions for this environment. As long as no
76 template was loaded it's safe to modify this dict. For custom tests
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
77 see :ref:`writing-tests`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
78
79 .. attribute:: globals
80
81 A dict of global variables. These variables are always available
82 in a template and (if the optimizer is enabled) may not be
ad48a2e Fixed typos in documentation
Lukas Meuser authored
83 overridden by templates. As long as no template was loaded it's safe
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
84 to modify this dict. For more details see :ref:`global-namespace`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
85
86
87 .. autoclass:: jinja2.Template
7ceced5 @mitsuhiko moved concat to utils, fixed a few docstrings, fixed memory leak in _…
authored
88 :members: render, stream, generate, make_module, module
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
89
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
90 .. attribute:: globals
91
92 foo
93
94 .. attribute:: name
95
96 foo
97
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
98
99 .. autoclass:: jinja2.environment.TemplateStream
100 :members: disable_buffering, enable_buffering
101
102
103 Undefined Types
104 ---------------
105
106 These classes can be used as undefined types. The :class:`Environment`
107 constructor takes an `undefined` parameter that can be one of those classes
108 or a custom subclass of :class:`Undefined`. Whenever the template engine is
109 unable to look up a name or access an attribute one of those objects is
110 created and returned. Some operations on undefined values are then allowed,
111 others fail.
112
113 The closest to regular Python behavior is the `StrictUndefined` which
114 disallows all operations beside testing if it's an undefined object.
115
116 .. autoclass:: jinja2.runtime.Undefined
117
118 .. autoclass:: jinja2.runtime.DebugUndefined
119
120 .. autoclass:: jinja2.runtime.StrictUndefined
121
122
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
123 The Context
124 -----------
125
19cf9c2 @mitsuhiko small performance improvements
authored
126 .. autoclass:: jinja2.runtime.Context
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into…
authored
127 :members: resolve, get_exported, get_all
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
128
129 .. attribute:: parent
130
131 A dict of read only, global variables the template looks up. These
19cf9c2 @mitsuhiko small performance improvements
authored
132 can either come from another :class:`Context`, from the
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
133 :attr:`Environment.globals` or :attr:`Template.globals`. It must not
134 be altered.
135
136 .. attribute:: vars
137
138 The template local variables. This list contains environment and
139 context functions from the :attr:`parent` scope as well as local
140 modifications and exported variables from the template. The template
141 will modify this dict during template evaluation but filters and
142 context functions are not allowed to modify it.
143
144 .. attribute:: environment
145
146 The environment that loaded the template.
147
148 .. attribute:: exported_vars
149
150 This set contains all the names the template exports. The values for
151 the names are in the :attr:`vars` dict. In order to get a copy of the
152 exported variables as dict, :meth:`get_exported` can be used.
153
154 .. attribute:: name
155
156 The load name of the template owning this context.
157
158 .. attribute:: blocks
159
160 A dict with the current mapping of blocks in the template. The keys
161 in this dict are the names of the blocks, and the values a list of
162 blocks registered. The last item in each list is the current active
163 block (latest in the inheritance chain).
164
165
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
166 Loaders
167 -------
168
169 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
170 file system. The environment will keep the compiled modules in memory like
171 Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
172 size by default and templates are automatically reloaded.
cda43df @mitsuhiko updated filters: wordwraps uses the wordwrap module and urlize marks …
authored
173 All loaders are subclasses of :class:`BaseLoader`. If you want to create your
174
175 own loader, subclass :class:`BaseLoader` and override `get_source`.
176
177 .. autoclass:: jinja2.loaders.BaseLoader
178 :members: get_source, load
179
180 Here a list of the builtin loaders Jinja2 provides:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
181
182 .. autoclass:: jinja2.loaders.FileSystemLoader
183
184 .. autoclass:: jinja2.loaders.PackageLoader
185
186 .. autoclass:: jinja2.loaders.DictLoader
187
188 .. autoclass:: jinja2.loaders.FunctionLoader
189
190 .. autoclass:: jinja2.loaders.PrefixLoader
191
192 .. autoclass:: jinja2.loaders.ChoiceLoader
193
194
195 Utilities
196 ---------
197
198 These helper functions and classes are useful if you add custom filters or
199 functions to a Jinja2 environment.
200
201 .. autofunction:: jinja2.filters.environmentfilter
202
203 .. autofunction:: jinja2.filters.contextfilter
204
205 .. autofunction:: jinja2.utils.environmentfunction
206
207 .. autofunction:: jinja2.utils.contextfunction
208
209 .. function:: escape(s)
210
211 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
212 Use this if you need to display text that might contain such characters
213 in HTML. This function will not escaped objects that do have an HTML
214 representation such as already escaped data.
215
187bde1 @mitsuhiko added cache_clear function
authored
216 .. autofunction:: jinja2.utils.clear_caches
217
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
218 .. autoclass:: jinja2.utils.Markup
219
220
221 Exceptions
222 ----------
223
224 .. autoclass:: jinja2.exceptions.TemplateError
225
226 .. autoclass:: jinja2.exceptions.UndefinedError
227
228 .. autoclass:: jinja2.exceptions.TemplateNotFound
229
230 .. autoclass:: jinja2.exceptions.TemplateSyntaxError
231
232 .. autoclass:: jinja2.exceptions.TemplateAssertionError
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
233
234
235 .. _writing-filters:
236
237 Custom Filters
238 --------------
239
240 Custom filters are just regular Python functions that take the left side of
241 the filter as first argument and the the arguments passed to the filter as
242 extra arguments or keyword arguments.
243
244 For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
245 called with ``myfilter(42, 23)``. Here for example a simple filter that can
246 be applied to datetime objects to format them::
247
248 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
249 return value.strftime(format)
250
251 You can register it on the template environment by updating the
252 :attr:`~Environment.filters` dict on the environment::
253
254 environment.filters['datetimeformat'] = datetimeformat
255
256 Inside the template it can then be used as follows:
257
258 .. sourcecode:: jinja
259
260 written on: {{ article.pub_date|datetimeformat }}
261 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
262
263 Filters can also be passed the current template context or environment. This
264 is useful if a filters wants to return an undefined value or check the current
265 :attr:`~Environment.autoescape` setting. For this purpose two decorators
266 exist: :func:`environmentfilter` and :func:`contextfilter`.
267
268 Here a small example filter that breaks a text into HTML line breaks and
269 paragraphs and marks the return value as safe HTML string if autoescaping is
270 enabled::
271
272 import re
273 from jinja2 import environmentfilter, Markup, escape
274
275 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
276
277 @environmentfilter
278 def nl2br(environment, value):
279 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
280 for p in _paragraph_re.split(escape(value)))
281 if environment.autoescape:
282 result = Markup(result)
283 return result
284
285 Context filters work the same just that the first argument is the current
19cf9c2 @mitsuhiko small performance improvements
authored
286 active :class:`Context` rather then the environment.
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
287
288
289 .. _writing-tests:
290
291 Custom Tests
292 ------------
293
294 Tests work like filters just that there is no way for a filter to get access
295 to the environment or context and that they can't be chained. The return
296 value of a filter should be `True` or `False`. The purpose of a filter is to
297 give the template designers the possibility to perform type and conformability
298 checks.
299
300 Here a simple filter that checks if a variable is a prime number::
301
302 import math
303
304 def is_prime(n):
305 if n == 2:
306 return True
307 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
308 if n % i == 0:
309 return False
310 return True
311
312
313 You can register it on the template environment by updating the
314 :attr:`~Environment.tests` dict on the environment::
315
316 environment.tests['prime'] = is_prime
317
318 A template designer can then use the test like this:
319
320 .. sourcecode:: jinja
321
322 {% if 42 is prime %}
323 42 is a prime number
324 {% else %}
325 42 is not a prime number
326 {% endif %}
327
328
329 .. _global-namespace:
330
331 The Global Namespace
332 --------------------
333
334 Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`
335 dicts are special as they are available for imported templates too and will be
336 used by the optimizer in future releases to evaluates parts of the template at
337 compile time. This is the place where you can put variables and functions
338 that should be available all the time.
Something went wrong with that request. Please try again.