Automated merge with http://dev.pocoo.org/hg/jinja2-main/
[jinja2.git] / docs / api.rst
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 albeit a shared one.
20
21 Most applications will create one :class:`Environment` object on application
22 initialization and use that to load templates.  In some cases it's however
23 useful to have multiple environments side by side, if different configurations
24 are in use.
25
26 The simplest way to configure Jinja2 to load templates for your application
27 looks roughly like this::
28
29     from jinja2 import Environment, PackageLoader
30     env = Environment(loader=PackageLoader('yourapplication', 'templates'))
31
32 This will create a template environment with the default settings and a
33 loader that looks up the templates in the `templates` folder inside the
34 `yourapplication` python package.  Different loaders are available
35 and you can also write your own if you want to load templates from a
36 database or other resources.
37
38 To load a template from this environment you just have to call the
39 :meth:`get_template` method which then returns the loaded :class:`Template`::
40
41     template = env.get_template('mytemplate.html')
42
43 To render it with some variables, just call the :meth:`render` method::
44
45     print template.render(the='variables', go='here')
46
47 Using a template loader rather then passing strings to :class:`Template`
48 or :meth:`Environment.from_string` has multiple advantages.  Besides being
49 a lot easier to use it also enables template inheritance.
50
51
52 Unicode
53 -------
54
55 Jinja2 is using unicode internally which means that you have to pass unicode
56 objects to the render function or bytestrings that only consist of ASCII
57 characters.  Additionally newlines are normalized to one end of line
58 sequence which is per default UNIX style (``\n``).
59
60 Python 2.x supports two ways of representing string objects.  One is the
61 `str` type and the other is the `unicode` type, both of which extend a type
62 called `basestring`.  Unfortunately the default is `str` which should not
63 be used to store text based information unless only ASCII characters are
64 used.  With Python 2.6 it is possible to my `unicode` the default on a per
65 module level and with Python 3 it will be the default.
66
67 To explicitly use a unicode string you have to prefix the string literal
68 with a `u`: ``u'Hänsel und Gretel sagen Hallo'``.  That way Python will
69 store the string as unicode by decoding the string with the character
70 encoding from the current Python module.  If no encoding is specified this
71 defaults to 'ASCII' which means that you can't use any non ASCII identifier.
72
73 To set a better module encoding add the following comment to the first or
74 second line of the Python module using the unicode literal::
75
76     # -*- coding: utf-8 -*-
77
78 We recommend utf-8 as Encoding for Python modules and templates as it's
79 possible to represent every Unicode character in utf-8 and because it's
80 backwards compatible to ASCII.  For Jinja2 the default encoding of templates
81 is assumed to be utf-8.
82
83 It is not possible to use Jinja2 to process non unicode data.  The reason
84 for this is that Jinja2 uses Unicode already on the language level.  For
85 example Jinja2 treats the non-breaking space as valid whitespace inside
86 expressions which requires knowledge of the encoding or operating on an
87 unicode string.
88
89 For more details about unicode in Python have a look at the excellent
90 `Unicode documentation`_.
91
92 Another important thing is how Jinja2 is handling string literals in
93 templates.  A naive implementation would be using unicode strings for
94 all string literals but it turned out in the past that this is problematic
95 as some libraries are typechecking against `str` explicitly.  For example
96 `datetime.strftime` does not accept unicode arguments.  To not break it
97 completely Jinja2 is returning `str` for strings that fit into ASCII and
98 for everything else `unicode`:
99
100 >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
101 >>> m.a
102 'foo'
103 >>> m.b
104 u'f\xf6\xf6'
105
106
107 .. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
108
109 High Level API
110 --------------
111
112 The high-level API is the API you will use in the application to load and
113 render Jinja2 templates.  The :ref:`low-level-api` on the other side is only
114 useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
115 <jinja-extensions>`.
116
117 .. autoclass:: Environment([options])
118     :members: from_string, get_template, join_path, extend
119
120     .. attribute:: shared
121
122         If a template was created by using the :class:`Template` constructor
123         an environment is created automatically.  These environments are
124         created as shared environments which means that multiple templates
125         may have the same anonymous environment.  For all shared environments
126         this attribute is `True`, else `False`.
127
128     .. attribute:: sandboxed
129
130         If the environment is sandboxed this attribute is `True`.  For the
131         sandbox mode have a look at the documentation for the
132         :class:`~jinja2.sandbox.SandboxedEnvironment`.
133
134     .. attribute:: filters
135
136         A dict of filters for this environment.  As long as no template was
137         loaded it's safe to add new filters or remove old.  For custom filters
138         see :ref:`writing-filters`.  For valid filter names have a look at
139         :ref:`identifier-naming`.
140
141     .. attribute:: tests
142
143         A dict of test functions for this environment.  As long as no
144         template was loaded it's safe to modify this dict.  For custom tests
145         see :ref:`writing-tests`.  For valid test names have a look at
146         :ref:`identifier-naming`.
147
148     .. attribute:: globals
149
150         A dict of global variables.  These variables are always available
151         in a template.  As long as no template was loaded it's safe
152         to modify this dict.  For more details see :ref:`global-namespace`.
153         For valid object names have a look at :ref:`identifier-naming`.
154
155     .. automethod:: overlay([options])
156
157     .. method:: undefined([hint, obj, name, exc])
158
159         Creates a new :class:`Undefined` object for `name`.  This is useful
160         for filters or functions that may return undefined objects for
161         some operations.  All parameters except of `hint` should be provided
162         as keyword parameters for better readability.  The `hint` is used as
163         error message for the exception if provided, otherwise the error
164         message generated from `obj` and `name` automatically.  The exception
165         provided as `exc` is raised if something with the generated undefined
166         object is done that the undefined object does not allow.  The default
167         exception is :exc:`UndefinedError`.  If a `hint` is provided the
168         `name` may be ommited.
169
170         The most common way to create an undefined object is by providing
171         a name only::
172
173             return environment.undefined(name='some_name')
174
175         This means that the name `some_name` is not defined.  If the name
176         was from an attribute of an object it makes sense to tell the
177         undefined object the holder object to improve the error message::
178
179             if not hasattr(obj, 'attr'):
180                 return environment.undefined(obj=obj, name='attr')
181
182         For a more complex example you can provide a hint.  For example
183         the :func:`first` filter creates an undefined object that way::
184
185             return environment.undefined('no first item, sequence was empty')            
186
187         If it the `name` or `obj` is known (for example because an attribute
188         was accessed) it shold be passed to the undefined object, even if
189         a custom `hint` is provided.  This gives undefined objects the
190         possibility to enhance the error message.
191
192 .. autoclass:: Template
193     :members: module, make_module
194
195     .. attribute:: globals
196
197         The dict with the globals of that template.  It's unsafe to modify
198         this dict as it may be shared with other templates or the environment
199         that loaded the template.
200
201     .. attribute:: name
202
203         The loading name of the template.  If the template was loaded from a
204         string this is `None`.
205
206     .. attribute:: filename
207
208         The filename of the template on the file system if it was loaded from
209         there.  Otherwise this is `None`.
210
211     .. automethod:: render([context])
212
213     .. automethod:: generate([context])
214
215     .. automethod:: stream([context])
216
217
218 .. autoclass:: jinja2.environment.TemplateStream()
219     :members: disable_buffering, enable_buffering, dump
220
221
222 .. _identifier-naming:
223
224 Notes on Identifiers
225 --------------------
226
227 Jinja2 uses the regular Python 2.x naming rules.  Valid identifiers have to
228 match ``[a-zA-Z_][a-zA-Z0-9_]*``.  As a matter of fact non ASCII characters
229 are currently not allowed.  This limitation will probably go away as soon as
230 unicode identifiers are fully specified for Python 3.
231
232 Filters and tests are looked up in separate namespaces and have slightly
233 modified identifier syntax.  Filters and tests may contain dots to group
234 filters and tests by topic.  For example it's perfectly valid to add a
235 function into the filter dict and call it `to.unicode`.  The regular
236 expression for filter and test identifiers is
237 ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
238
239
240 Undefined Types
241 ---------------
242
243 These classes can be used as undefined types.  The :class:`Environment`
244 constructor takes an `undefined` parameter that can be one of those classes
245 or a custom subclass of :class:`Undefined`.  Whenever the template engine is
246 unable to look up a name or access an attribute one of those objects is
247 created and returned.  Some operations on undefined values are then allowed,
248 others fail.
249
250 The closest to regular Python behavior is the `StrictUndefined` which
251 disallows all operations beside testing if it's an undefined object.
252
253 .. autoclass:: jinja2.runtime.Undefined()
254
255     .. attribute:: _undefined_hint
256
257         Either `None` or an unicode string with the error message for
258         the undefined object.
259
260     .. attribute:: _undefined_obj
261
262         Either `None` or the owner object that caused the undefined object
263         to be created (for example because an attribute does not exist).
264
265     .. attribute:: _undefined_name
266
267         The name for the undefined variable / attribute or just `None`
268         if no such information exists.
269
270     .. attribute:: _undefined_exception
271
272         The exception that the undefined object wants to raise.  This
273         is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
274
275     .. method:: _fail_with_undefined_error(\*args, \**kwargs)
276
277         When called with any arguments this method raises
278         :attr:`_undefined_exception` with an error message generated
279         from the undefined hints stored on the undefined object.
280
281 .. autoclass:: jinja2.runtime.DebugUndefined()
282
283 .. autoclass:: jinja2.runtime.StrictUndefined()
284
285 Undefined objects are created by calling :attr:`undefined`.
286
287 .. admonition:: Implementation
288
289     :class:`Undefined` objects are implemented by overriding the special
290     `__underscore__` methods.  For example the default :class:`Undefined`
291     class implements `__unicode__` in a way that it returns an empty
292     string, however `__int__` and others still fail with an exception.  To
293     allow conversion to int by returning ``0`` you can implement your own::
294
295         class NullUndefined(Undefined):
296             def __int__(self):
297                 return 0
298             def __float__(self):
299                 return 0.0
300
301     To disallow a method, just override it and raise
302     :attr:`~Undefined._undefined_exception`.  Because this is a very common
303     idom in undefined objects there is the helper method
304     :meth:`~Undefined._fail_with_undefined_error` that does the error raising
305     automatically.  Here a class that works like the regular :class:`Undefined`
306     but chokes on iteration::
307
308         class NonIterableUndefined(Undefined):
309             __iter__ = Undefined._fail_with_undefined_error
310
311
312 The Context
313 -----------
314
315 .. autoclass:: jinja2.runtime.Context()
316     :members: resolve, get_exported, get_all
317
318     .. attribute:: parent
319
320         A dict of read only, global variables the template looks up.  These
321         can either come from another :class:`Context`, from the
322         :attr:`Environment.globals` or :attr:`Template.globals` or points
323         to a dict created by combining the globals with the variables
324         passed to the render function.  It must not be altered.
325
326     .. attribute:: vars
327
328         The template local variables.  This list contains environment and
329         context functions from the :attr:`parent` scope as well as local
330         modifications and exported variables from the template.  The template
331         will modify this dict during template evaluation but filters and
332         context functions are not allowed to modify it.
333
334     .. attribute:: environment
335
336         The environment that loaded the template.
337
338     .. attribute:: exported_vars
339
340         This set contains all the names the template exports.  The values for
341         the names are in the :attr:`vars` dict.  In order to get a copy of the
342         exported variables as dict, :meth:`get_exported` can be used.
343
344     .. attribute:: name
345
346         The load name of the template owning this context.
347
348     .. attribute:: blocks
349
350         A dict with the current mapping of blocks in the template.  The keys
351         in this dict are the names of the blocks, and the values a list of
352         blocks registered.  The last item in each list is the current active
353         block (latest in the inheritance chain).
354
355     .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
356
357
358 .. admonition:: Implementation
359
360     Context is immutable for the same reason Python's frame locals are
361     immutable inside functions.  Both Jinja2 and Python are not using the
362     context / frame locals as data storage for variables but only as primary
363     data source.
364
365     When a template accesses a variable the template does not define, Jinja2
366     looks up the variable in the context, after that the variable is treated
367     as if it was defined in the template.
368
369
370 .. _loaders:
371
372 Loaders
373 -------
374
375 Loaders are responsible for loading templates from a resource such as the
376 file system.  The environment will keep the compiled modules in memory like
377 Python's `sys.modules`.  Unlike `sys.modules` however this cache is limited in
378 size by default and templates are automatically reloaded.
379 All loaders are subclasses of :class:`BaseLoader`.  If you want to create your
380 own loader, subclass :class:`BaseLoader` and override `get_source`.
381
382 .. autoclass:: jinja2.loaders.BaseLoader
383     :members: get_source, load
384
385 Here a list of the builtin loaders Jinja2 provides:
386
387 .. autoclass:: jinja2.loaders.FileSystemLoader
388
389 .. autoclass:: jinja2.loaders.PackageLoader
390
391 .. autoclass:: jinja2.loaders.DictLoader
392
393 .. autoclass:: jinja2.loaders.FunctionLoader
394
395 .. autoclass:: jinja2.loaders.PrefixLoader
396
397 .. autoclass:: jinja2.loaders.ChoiceLoader
398
399
400 Utilities
401 ---------
402
403 These helper functions and classes are useful if you add custom filters or
404 functions to a Jinja2 environment.
405
406 .. autofunction:: jinja2.filters.environmentfilter
407
408 .. autofunction:: jinja2.filters.contextfilter
409
410 .. autofunction:: jinja2.utils.environmentfunction
411
412 .. autofunction:: jinja2.utils.contextfunction
413
414 .. function:: escape(s)
415
416     Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
417     to HTML-safe sequences.  Use this if you need to display text that might
418     contain such characters in HTML.  This function will not escaped objects
419     that do have an HTML representation such as already escaped data.
420
421     The return value is a :class:`Markup` string.
422
423 .. autofunction:: jinja2.utils.clear_caches
424
425 .. autofunction:: jinja2.utils.is_undefined
426
427 .. autoclass:: jinja2.utils.Markup([string])
428     :members: escape, unescape, striptags
429
430 .. admonition:: Note
431
432     The Jinja2 :class:`Markup` class is compatible with at least Pylons and
433     Genshi.  It's expected that more template engines and framework will pick
434     up the `__html__` concept soon.
435
436
437 Exceptions
438 ----------
439
440 .. autoexception:: jinja2.exceptions.TemplateError
441
442 .. autoexception:: jinja2.exceptions.UndefinedError
443
444 .. autoexception:: jinja2.exceptions.TemplateNotFound
445
446 .. autoexception:: jinja2.exceptions.TemplateSyntaxError
447
448     .. attribute:: message
449
450         The error message as utf-8 bytestring.
451
452     .. attribute:: lineno
453
454         The line number where the error occurred
455
456     .. attribute:: name
457
458         The load name for the template as unicode string.
459
460     .. attribute:: filename
461
462         The filename that loaded the template as bytestring in the encoding
463         of the file system (most likely utf-8 or mbcs on Windows systems).
464
465     The reason why the filename and error message are bytestrings and not
466     unicode strings is that Python 2.x is not using unicode for exceptions
467     and tracebacks as well as the compiler.  This will change with Python 3.
468
469 .. autoexception:: jinja2.exceptions.TemplateAssertionError
470
471
472 .. _writing-filters:
473
474 Custom Filters
475 --------------
476
477 Custom filters are just regular Python functions that take the left side of
478 the filter as first argument and the the arguments passed to the filter as
479 extra arguments or keyword arguments.
480
481 For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
482 called with ``myfilter(42, 23)``.  Here for example a simple filter that can
483 be applied to datetime objects to format them::
484
485     def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
486         return value.strftime(format)
487
488 You can register it on the template environment by updating the
489 :attr:`~Environment.filters` dict on the environment::
490
491     environment.filters['datetimeformat'] = datetimeformat
492
493 Inside the template it can then be used as follows:
494
495 .. sourcecode:: jinja
496
497     written on: {{ article.pub_date|datetimeformat }}
498     publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
499
500 Filters can also be passed the current template context or environment.  This
501 is useful if a filters wants to return an undefined value or check the current
502 :attr:`~Environment.autoescape` setting.  For this purpose two decorators
503 exist: :func:`environmentfilter` and :func:`contextfilter`.
504
505 Here a small example filter that breaks a text into HTML line breaks and
506 paragraphs and marks the return value as safe HTML string if autoescaping is
507 enabled::
508
509     import re
510     from jinja2 import environmentfilter, Markup, escape
511
512     _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
513
514     @environmentfilter
515     def nl2br(environment, value):
516         result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
517                               for p in _paragraph_re.split(escape(value)))
518         if environment.autoescape:
519             result = Markup(result)
520         return result
521
522 Context filters work the same just that the first argument is the current
523 active :class:`Context` rather then the environment.
524
525
526 .. _writing-tests:
527
528 Custom Tests
529 ------------
530
531 Tests work like filters just that there is no way for a filter to get access
532 to the environment or context and that they can't be chained.  The return
533 value of a filter should be `True` or `False`.  The purpose of a filter is to
534 give the template designers the possibility to perform type and conformability
535 checks.
536
537 Here a simple filter that checks if a variable is a prime number::
538
539     import math
540
541     def is_prime(n):
542         if n == 2:
543             return True
544         for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
545             if n % i == 0:
546                 return False
547         return True
548         
549
550 You can register it on the template environment by updating the
551 :attr:`~Environment.tests` dict on the environment::
552
553     environment.tests['prime'] = is_prime
554
555 A template designer can then use the test like this:
556
557 .. sourcecode:: jinja
558
559     {% if 42 is prime %}
560         42 is a prime number
561     {% else %}
562         42 is not a prime number
563     {% endif %}
564
565
566 .. _global-namespace:
567
568 The Global Namespace
569 --------------------
570
571 Variables stored in the :attr:`Environment.globals` dict are special as they
572 are available for imported templates too, even if they are imported without
573 context.  This is the place where you can put variables and functions
574 that should be available all the time.  Additionally :attr:`Template.globals`
575 exist that are variables available to a specific template that are available
576 to all :meth:`~Template.render` calls.
577
578
579 .. _low-level-api:
580
581 Low Level API
582 -------------
583
584 The low level API exposes functionality that can be useful to understand some
585 implementation details, debugging purposes or advanced :ref:`extension
586 <jinja-extensions>` techniques.  Unless you know exactly what you are doing we
587 don't recommend using any of those.
588
589 .. automethod:: Environment.lex
590
591 .. automethod:: Environment.parse
592
593 .. automethod:: Environment.preprocess
594
595 .. automethod:: Template.new_context
596
597 .. method:: Template.root_render_func(context)
598
599     This is the low level render function.  It's passed a :class:`Context`
600     that has to be created by :meth:`new_context` of the same template or
601     a compatible template.  This render function is generated by the
602     compiler from the template code and returns a generator that yields
603     unicode strings.
604
605     If an exception in the template code happens the template engine will
606     not rewrite the exception but pass through the original one.  As a
607     matter of fact this function should only be called from within a
608     :meth:`render` / :meth:`generate` / :meth:`stream` call.
609
610 .. attribute:: Template.blocks
611
612     A dict of block render functions.  Each of these functions works exactly
613     like the :meth:`root_render_func` with the same limitations.
614
615 .. attribute:: Template.is_up_to_date
616
617     This attribute is `False` if there is a newer version of the template
618     available, otherwise `True`.
619
620 .. admonition:: Note
621
622     The low-level API is fragile.  Future Jinja2 versions will try not to
623     change it in a backwards incompatible way but modifications in the Jinja2
624     core may shine through.  For example if Jinja2 introduces a new AST node
625     in later versions that may be returned by :meth:`~Environment.parse`.