5 :synopsis: public Jinja2 API
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.
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.
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
25 The simplest way to configure Jinja2 to load templates for your application
26 looks roughly like this::
28 from jinja2 import Environment, PackageLoader
29 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
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.
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`::
40 template = env.get_template('mytemplate.html')
42 To render it with some variables, just call the :meth:`render` method::
44 print template.render(the='variables', go='here')
50 .. autoclass:: jinja2.environment.Environment([options])
51 :members: from_string, get_template, join_path, parse, lex, extend
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`.
61 .. attribute:: sandboxed
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`.
67 .. attribute:: filters
69 A dict of filters for this environment. As long as no template was
70 loaded it's safe to add new filters or remove old. For custom filters
71 see :ref:`writing-filters`.
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
77 see :ref:`writing-tests`.
79 .. attribute:: globals
81 A dict of global variables. These variables are always available
82 in a template and (if the optimizer is enabled) may not be
83 overridden by templates. As long as no template was loaded it's safe
84 to modify this dict. For more details see :ref:`global-namespace`.
86 .. automethod:: overlay([options])
89 .. autoclass:: jinja2.Template
90 :members: make_module, module, new_context
92 .. attribute:: globals
94 The dict with the globals of that template. It's unsafe to modify
95 this dict as it may be shared with other templates or the environment
96 that loaded the template.
100 The loading name of the template. If the template was loaded from a
101 string this is `None`.
103 .. automethod:: render([context])
105 .. automethod:: generate([context])
107 .. automethod:: stream([context])
110 .. autoclass:: jinja2.environment.TemplateStream
111 :members: disable_buffering, enable_buffering
117 These classes can be used as undefined types. The :class:`Environment`
118 constructor takes an `undefined` parameter that can be one of those classes
119 or a custom subclass of :class:`Undefined`. Whenever the template engine is
120 unable to look up a name or access an attribute one of those objects is
121 created and returned. Some operations on undefined values are then allowed,
124 The closest to regular Python behavior is the `StrictUndefined` which
125 disallows all operations beside testing if it's an undefined object.
127 .. autoclass:: jinja2.runtime.Undefined
129 .. autoclass:: jinja2.runtime.DebugUndefined
131 .. autoclass:: jinja2.runtime.StrictUndefined
137 .. autoclass:: jinja2.runtime.Context
138 :members: resolve, get_exported, get_all
140 .. attribute:: parent
142 A dict of read only, global variables the template looks up. These
143 can either come from another :class:`Context`, from the
144 :attr:`Environment.globals` or :attr:`Template.globals`. It must not
149 The template local variables. This list contains environment and
150 context functions from the :attr:`parent` scope as well as local
151 modifications and exported variables from the template. The template
152 will modify this dict during template evaluation but filters and
153 context functions are not allowed to modify it.
155 .. attribute:: environment
157 The environment that loaded the template.
159 .. attribute:: exported_vars
161 This set contains all the names the template exports. The values for
162 the names are in the :attr:`vars` dict. In order to get a copy of the
163 exported variables as dict, :meth:`get_exported` can be used.
167 The load name of the template owning this context.
169 .. attribute:: blocks
171 A dict with the current mapping of blocks in the template. The keys
172 in this dict are the names of the blocks, and the values a list of
173 blocks registered. The last item in each list is the current active
174 block (latest in the inheritance chain).
182 Loaders are responsible for loading templates from a resource such as the
183 file system. The environment will keep the compiled modules in memory like
184 Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
185 size by default and templates are automatically reloaded.
186 All loaders are subclasses of :class:`BaseLoader`. If you want to create your
187 own loader, subclass :class:`BaseLoader` and override `get_source`.
189 .. autoclass:: jinja2.loaders.BaseLoader
190 :members: get_source, load
192 Here a list of the builtin loaders Jinja2 provides:
194 .. autoclass:: jinja2.loaders.FileSystemLoader
196 .. autoclass:: jinja2.loaders.PackageLoader
198 .. autoclass:: jinja2.loaders.DictLoader
200 .. autoclass:: jinja2.loaders.FunctionLoader
202 .. autoclass:: jinja2.loaders.PrefixLoader
204 .. autoclass:: jinja2.loaders.ChoiceLoader
210 These helper functions and classes are useful if you add custom filters or
211 functions to a Jinja2 environment.
213 .. autofunction:: jinja2.filters.environmentfilter
215 .. autofunction:: jinja2.filters.contextfilter
217 .. autofunction:: jinja2.utils.environmentfunction
219 .. autofunction:: jinja2.utils.contextfunction
221 .. function:: escape(s)
223 Convert the characters &, <, >, and " in string s to HTML-safe sequences.
224 Use this if you need to display text that might contain such characters
225 in HTML. This function will not escaped objects that do have an HTML
226 representation such as already escaped data.
228 .. autofunction:: jinja2.utils.clear_caches
230 .. autoclass:: jinja2.utils.Markup
236 .. autoexception:: jinja2.exceptions.TemplateError
238 .. autoexception:: jinja2.exceptions.UndefinedError
240 .. autoexception:: jinja2.exceptions.TemplateNotFound
242 .. autoexception:: jinja2.exceptions.TemplateSyntaxError
244 .. autoexception:: jinja2.exceptions.TemplateAssertionError
252 Custom filters are just regular Python functions that take the left side of
253 the filter as first argument and the the arguments passed to the filter as
254 extra arguments or keyword arguments.
256 For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
257 called with ``myfilter(42, 23)``. Here for example a simple filter that can
258 be applied to datetime objects to format them::
260 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
261 return value.strftime(format)
263 You can register it on the template environment by updating the
264 :attr:`~Environment.filters` dict on the environment::
266 environment.filters['datetimeformat'] = datetimeformat
268 Inside the template it can then be used as follows:
270 .. sourcecode:: jinja
272 written on: {{ article.pub_date|datetimeformat }}
273 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
275 Filters can also be passed the current template context or environment. This
276 is useful if a filters wants to return an undefined value or check the current
277 :attr:`~Environment.autoescape` setting. For this purpose two decorators
278 exist: :func:`environmentfilter` and :func:`contextfilter`.
280 Here a small example filter that breaks a text into HTML line breaks and
281 paragraphs and marks the return value as safe HTML string if autoescaping is
285 from jinja2 import environmentfilter, Markup, escape
287 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
290 def nl2br(environment, value):
291 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
292 for p in _paragraph_re.split(escape(value)))
293 if environment.autoescape:
294 result = Markup(result)
297 Context filters work the same just that the first argument is the current
298 active :class:`Context` rather then the environment.
306 Tests work like filters just that there is no way for a filter to get access
307 to the environment or context and that they can't be chained. The return
308 value of a filter should be `True` or `False`. The purpose of a filter is to
309 give the template designers the possibility to perform type and conformability
312 Here a simple filter that checks if a variable is a prime number::
319 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
325 You can register it on the template environment by updating the
326 :attr:`~Environment.tests` dict on the environment::
328 environment.tests['prime'] = is_prime
330 A template designer can then use the test like this:
332 .. sourcecode:: jinja
337 42 is not a prime number
341 .. _global-namespace:
346 Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`
347 dicts are special as they are available for imported templates too and will be
348 used by the optimizer in future releases to evaluates parts of the template at
349 compile time. This is the place where you can put variables and functions
350 that should be available all the time.