| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 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`. |
| Carl A Dunham | d546358 | 2014-01-18 15:26:10 -0600 | [diff] [blame] | 15 | Instances of this class are used to store the configuration and global objects, |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 16 | and are used to load templates from the file system or other locations. |
| Armin Ronacher | 0aa0f58 | 2009-03-18 01:01:36 +0100 | [diff] [blame] | 17 | Even if you are creating templates from strings by using the constructor of |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 18 | :class:`Template` class, an environment is created automatically for you, |
| 19 | albeit a shared one. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 20 | |
| 21 | Most applications will create one :class:`Environment` object on application |
| Kojo Idrissa | d48cb21 | 2016-04-10 14:04:46 -0500 | [diff] [blame] | 22 | initialization and use that to load templates. In some cases however, it's |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 29 | from jinja2 import Environment, PackageLoader, select_autoescape |
| 30 | env = Environment( |
| 31 | loader=PackageLoader('yourapplication', 'templates'), |
| 32 | autoescape=select_autoescape(['html', 'xml']) |
| 33 | ) |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 34 | |
| 35 | This will create a template environment with the default settings and a |
| 36 | loader that looks up the templates in the `templates` folder inside the |
| 37 | `yourapplication` python package. Different loaders are available |
| 38 | and you can also write your own if you want to load templates from a |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 39 | database or other resources. This also enables autoescaping for HTML and |
| 40 | XML files. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 41 | |
| 42 | To load a template from this environment you just have to call the |
| 43 | :meth:`get_template` method which then returns the loaded :class:`Template`:: |
| 44 | |
| 45 | template = env.get_template('mytemplate.html') |
| 46 | |
| 47 | To render it with some variables, just call the :meth:`render` method:: |
| 48 | |
| 49 | print template.render(the='variables', go='here') |
| 50 | |
| Éric Araujo | f6b654d | 2015-05-29 16:57:10 -0400 | [diff] [blame] | 51 | Using a template loader rather than passing strings to :class:`Template` |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 52 | or :meth:`Environment.from_string` has multiple advantages. Besides being |
| 53 | a lot easier to use it also enables template inheritance. |
| 54 | |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 55 | .. admonition:: Notes on Autoescaping |
| 56 | |
| 57 | In future versions of Jinja2 we might enable autoescaping by default |
| 58 | for security reasons. As such you are encouraged to explicitly |
| 59 | configure autoescaping now instead of relying on the default. |
| 60 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 61 | |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 62 | Unicode |
| 63 | ------- |
| 64 | |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 65 | Jinja2 is using Unicode internally which means that you have to pass Unicode |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 66 | objects to the render function or bytestrings that only consist of ASCII |
| 67 | characters. Additionally newlines are normalized to one end of line |
| 68 | sequence which is per default UNIX style (``\n``). |
| 69 | |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 70 | Python 2.x supports two ways of representing string objects. One is the |
| 71 | `str` type and the other is the `unicode` type, both of which extend a type |
| 72 | called `basestring`. Unfortunately the default is `str` which should not |
| 73 | be used to store text based information unless only ASCII characters are |
| Armin Ronacher | 0aa0f58 | 2009-03-18 01:01:36 +0100 | [diff] [blame] | 74 | used. With Python 2.6 it is possible to make `unicode` the default on a per |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 75 | module level and with Python 3 it will be the default. |
| 76 | |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 77 | To explicitly use a Unicode string you have to prefix the string literal |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 78 | with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 79 | store the string as Unicode by decoding the string with the character |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 80 | encoding from the current Python module. If no encoding is specified this |
| 81 | defaults to 'ASCII' which means that you can't use any non ASCII identifier. |
| 82 | |
| 83 | To set a better module encoding add the following comment to the first or |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 84 | second line of the Python module using the Unicode literal:: |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 85 | |
| 86 | # -*- coding: utf-8 -*- |
| 87 | |
| 88 | We recommend utf-8 as Encoding for Python modules and templates as it's |
| 89 | possible to represent every Unicode character in utf-8 and because it's |
| 90 | backwards compatible to ASCII. For Jinja2 the default encoding of templates |
| 91 | is assumed to be utf-8. |
| 92 | |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 93 | It is not possible to use Jinja2 to process non-Unicode data. The reason |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 94 | for this is that Jinja2 uses Unicode already on the language level. For |
| 95 | example Jinja2 treats the non-breaking space as valid whitespace inside |
| 96 | expressions which requires knowledge of the encoding or operating on an |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 97 | Unicode string. |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 98 | |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 99 | For more details about Unicode in Python have a look at the excellent |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 100 | `Unicode documentation`_. |
| 101 | |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 102 | Another important thing is how Jinja2 is handling string literals in |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 103 | templates. A naive implementation would be using Unicode strings for |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 104 | all string literals but it turned out in the past that this is problematic |
| 105 | as some libraries are typechecking against `str` explicitly. For example |
| Armin Ronacher | 656d5e7 | 2010-02-09 01:31:47 +0100 | [diff] [blame] | 106 | `datetime.strftime` does not accept Unicode arguments. To not break it |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 107 | completely Jinja2 is returning `str` for strings that fit into ASCII and |
| 108 | for everything else `unicode`: |
| 109 | |
| 110 | >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module |
| 111 | >>> m.a |
| 112 | 'foo' |
| 113 | >>> m.b |
| 114 | u'f\xf6\xf6' |
| 115 | |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 116 | |
| 117 | .. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 118 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 119 | High Level API |
| 120 | -------------- |
| 121 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 122 | The high-level API is the API you will use in the application to load and |
| 123 | render Jinja2 templates. The :ref:`low-level-api` on the other side is only |
| 124 | useful if you want to dig deeper into Jinja2 or :ref:`develop extensions |
| 125 | <jinja-extensions>`. |
| 126 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 127 | .. autoclass:: Environment([options]) |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 128 | :members: from_string, get_template, select_template, |
| Armin Ronacher | 4684498 | 2011-01-29 20:19:58 +0100 | [diff] [blame] | 129 | get_or_select_template, join_path, extend, compile_expression, |
| Armin Ronacher | 9463850 | 2011-09-26 00:41:25 +0200 | [diff] [blame] | 130 | compile_templates, list_templates, add_extension |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 131 | |
| 132 | .. attribute:: shared |
| 133 | |
| 134 | If a template was created by using the :class:`Template` constructor |
| 135 | an environment is created automatically. These environments are |
| 136 | created as shared environments which means that multiple templates |
| 137 | may have the same anonymous environment. For all shared environments |
| 138 | this attribute is `True`, else `False`. |
| 139 | |
| 140 | .. attribute:: sandboxed |
| 141 | |
| 142 | If the environment is sandboxed this attribute is `True`. For the |
| 143 | sandbox mode have a look at the documentation for the |
| 144 | :class:`~jinja2.sandbox.SandboxedEnvironment`. |
| 145 | |
| 146 | .. attribute:: filters |
| 147 | |
| 148 | A dict of filters for this environment. As long as no template was |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 149 | loaded it's safe to add new filters or remove old. For custom filters |
| Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 150 | see :ref:`writing-filters`. For valid filter names have a look at |
| 151 | :ref:`identifier-naming`. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 152 | |
| 153 | .. attribute:: tests |
| 154 | |
| Lukas Meuser | ad48a2e | 2008-05-01 18:19:57 +0200 | [diff] [blame] | 155 | A dict of test functions for this environment. As long as no |
| 156 | template was loaded it's safe to modify this dict. For custom tests |
| Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 157 | see :ref:`writing-tests`. For valid test names have a look at |
| 158 | :ref:`identifier-naming`. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 159 | |
| 160 | .. attribute:: globals |
| 161 | |
| 162 | A dict of global variables. These variables are always available |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 163 | in a template. As long as no template was loaded it's safe |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 164 | to modify this dict. For more details see :ref:`global-namespace`. |
| Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 165 | For valid object names have a look at :ref:`identifier-naming`. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 166 | |
| Armin Ronacher | e253520 | 2016-12-31 00:43:50 +0100 | [diff] [blame] | 167 | .. attribute:: policies |
| 168 | |
| 169 | A dictionary with :ref:`policies`. These can be reconfigured to |
| 170 | change the runtime behavior or certain template features. Usually |
| 171 | these are security related. |
| 172 | |
| ThiefMaster | 1493631 | 2015-04-06 13:54:14 +0200 | [diff] [blame] | 173 | .. attribute:: code_generator_class |
| 174 | |
| 175 | The class used for code generation. This should not be changed |
| 176 | in most cases, unless you need to modify the Python code a |
| 177 | template compiles to. |
| 178 | |
| ThiefMaster | f22fdd5 | 2015-04-06 14:08:46 +0200 | [diff] [blame] | 179 | .. attribute:: context_class |
| 180 | |
| 181 | The context used for templates. This should not be changed |
| 182 | in most cases, unless you need to modify internals of how |
| 183 | template variables are handled. For details, see |
| 184 | :class:`~jinja2.runtime.Context`. |
| 185 | |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 186 | .. automethod:: overlay([options]) |
| 187 | |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 188 | .. method:: undefined([hint, obj, name, exc]) |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 189 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 190 | Creates a new :class:`Undefined` object for `name`. This is useful |
| 191 | for filters or functions that may return undefined objects for |
| 192 | some operations. All parameters except of `hint` should be provided |
| 193 | as keyword parameters for better readability. The `hint` is used as |
| 194 | error message for the exception if provided, otherwise the error |
| Armin Ronacher | 0aa0f58 | 2009-03-18 01:01:36 +0100 | [diff] [blame] | 195 | message will be generated from `obj` and `name` automatically. The exception |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 196 | provided as `exc` is raised if something with the generated undefined |
| 197 | object is done that the undefined object does not allow. The default |
| 198 | exception is :exc:`UndefinedError`. If a `hint` is provided the |
| Alex Chan | 972c030 | 2015-04-05 22:42:34 +0100 | [diff] [blame] | 199 | `name` may be omitted. |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 200 | |
| 201 | The most common way to create an undefined object is by providing |
| 202 | a name only:: |
| 203 | |
| 204 | return environment.undefined(name='some_name') |
| 205 | |
| 206 | This means that the name `some_name` is not defined. If the name |
| 207 | was from an attribute of an object it makes sense to tell the |
| 208 | undefined object the holder object to improve the error message:: |
| 209 | |
| 210 | if not hasattr(obj, 'attr'): |
| 211 | return environment.undefined(obj=obj, name='attr') |
| 212 | |
| 213 | For a more complex example you can provide a hint. For example |
| 214 | the :func:`first` filter creates an undefined object that way:: |
| 215 | |
| 216 | return environment.undefined('no first item, sequence was empty') |
| 217 | |
| 218 | If it the `name` or `obj` is known (for example because an attribute |
| Alex Chan | 972c030 | 2015-04-05 22:42:34 +0100 | [diff] [blame] | 219 | was accessed) it should be passed to the undefined object, even if |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 220 | a custom `hint` is provided. This gives undefined objects the |
| 221 | possibility to enhance the error message. |
| 222 | |
| 223 | .. autoclass:: Template |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 224 | :members: module, make_module |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 225 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 226 | .. attribute:: globals |
| 227 | |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 228 | The dict with the globals of that template. It's unsafe to modify |
| 229 | this dict as it may be shared with other templates or the environment |
| 230 | that loaded the template. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 231 | |
| 232 | .. attribute:: name |
| 233 | |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 234 | The loading name of the template. If the template was loaded from a |
| 235 | string this is `None`. |
| 236 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 237 | .. attribute:: filename |
| 238 | |
| 239 | The filename of the template on the file system if it was loaded from |
| 240 | there. Otherwise this is `None`. |
| 241 | |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 242 | .. automethod:: render([context]) |
| 243 | |
| 244 | .. automethod:: generate([context]) |
| 245 | |
| 246 | .. automethod:: stream([context]) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 247 | |
| Armin Ronacher | d8326d9 | 2016-12-28 22:51:46 +0100 | [diff] [blame] | 248 | .. automethod:: render_async([context]) |
| 249 | |
| 250 | .. automethod:: generate_async([context]) |
| 251 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 252 | |
| Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame] | 253 | .. autoclass:: jinja2.environment.TemplateStream() |
| Armin Ronacher | 74b5106 | 2008-06-17 11:28:59 +0200 | [diff] [blame] | 254 | :members: disable_buffering, enable_buffering, dump |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 255 | |
| 256 | |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 257 | Autoescaping |
| 258 | ------------ |
| 259 | |
| Armin Ronacher | a27a503 | 2017-01-07 15:55:20 +0100 | [diff] [blame] | 260 | .. versionchanged:: 2.4 |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 261 | |
| Armin Ronacher | a27a503 | 2017-01-07 15:55:20 +0100 | [diff] [blame] | 262 | Jinja2 now comes with autoescaping support. As of Jinja 2.9 the |
| 263 | autoescape extension is removed and built-in. However autoescaping is |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 264 | not yet enabled by default though this will most likely change in the |
| 265 | future. It's recommended to configure a sensible default for |
| 266 | autoescaping. This makes it possible to enable and disable autoescaping |
| 267 | on a per-template basis (HTML versus text for instance). |
| 268 | |
| 269 | .. autofunction:: jinja2.select_autoescape |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 270 | |
| 271 | Here a recommended setup that enables autoescaping for templates ending |
| 272 | in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 273 | for all other extensions. You can use the :func:`~jinja2.select_autoescape` |
| 274 | function for this:: |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 275 | |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 276 | from jinja2 import Environment, select_autoescape |
| 277 | env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']), |
| Armin Ronacher | a27a503 | 2017-01-07 15:55:20 +0100 | [diff] [blame] | 278 | loader=PackageLoader('mypackage')) |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 279 | |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 280 | The :func:`~jinja.select_autoescape` function returns a function that |
| 281 | works rougly like this:: |
| 282 | |
| 283 | def autoescape(template_name): |
| 284 | if template_name is None: |
| 285 | return False |
| 286 | if template_name.endswith(('.html', '.htm', '.xml')) |
| 287 | |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 288 | When implementing a guessing autoescape function, make sure you also |
| 289 | accept `None` as valid template name. This will be passed when generating |
| Armin Ronacher | b81a8a3 | 2017-01-07 16:13:39 +0100 | [diff] [blame^] | 290 | templates from strings. You should always configure autoescaping as |
| 291 | defaults in the future might change. |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 292 | |
| 293 | Inside the templates the behaviour can be temporarily changed by using |
| 294 | the `autoescape` block (see :ref:`autoescape-overrides`). |
| 295 | |
| 296 | |
| Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 297 | .. _identifier-naming: |
| 298 | |
| 299 | Notes on Identifiers |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 300 | -------------------- |
| Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 301 | |
| 302 | Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to |
| 303 | match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters |
| 304 | are currently not allowed. This limitation will probably go away as soon as |
| 305 | unicode identifiers are fully specified for Python 3. |
| 306 | |
| 307 | Filters and tests are looked up in separate namespaces and have slightly |
| 308 | modified identifier syntax. Filters and tests may contain dots to group |
| 309 | filters and tests by topic. For example it's perfectly valid to add a |
| 310 | function into the filter dict and call it `to.unicode`. The regular |
| 311 | expression for filter and test identifiers is |
| 312 | ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. |
| 313 | |
| 314 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 315 | Undefined Types |
| 316 | --------------- |
| 317 | |
| 318 | These classes can be used as undefined types. The :class:`Environment` |
| 319 | constructor takes an `undefined` parameter that can be one of those classes |
| 320 | or a custom subclass of :class:`Undefined`. Whenever the template engine is |
| 321 | unable to look up a name or access an attribute one of those objects is |
| 322 | created and returned. Some operations on undefined values are then allowed, |
| 323 | others fail. |
| 324 | |
| 325 | The closest to regular Python behavior is the `StrictUndefined` which |
| 326 | disallows all operations beside testing if it's an undefined object. |
| 327 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 328 | .. autoclass:: jinja2.Undefined() |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 329 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 330 | .. attribute:: _undefined_hint |
| 331 | |
| 332 | Either `None` or an unicode string with the error message for |
| 333 | the undefined object. |
| 334 | |
| 335 | .. attribute:: _undefined_obj |
| 336 | |
| 337 | Either `None` or the owner object that caused the undefined object |
| 338 | to be created (for example because an attribute does not exist). |
| 339 | |
| 340 | .. attribute:: _undefined_name |
| 341 | |
| 342 | The name for the undefined variable / attribute or just `None` |
| 343 | if no such information exists. |
| 344 | |
| 345 | .. attribute:: _undefined_exception |
| 346 | |
| 347 | The exception that the undefined object wants to raise. This |
| 348 | is usually one of :exc:`UndefinedError` or :exc:`SecurityError`. |
| 349 | |
| 350 | .. method:: _fail_with_undefined_error(\*args, \**kwargs) |
| 351 | |
| 352 | When called with any arguments this method raises |
| 353 | :attr:`_undefined_exception` with an error message generated |
| 354 | from the undefined hints stored on the undefined object. |
| 355 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 356 | .. autoclass:: jinja2.DebugUndefined() |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 357 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 358 | .. autoclass:: jinja2.StrictUndefined() |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 359 | |
| Armin Ronacher | 6e9dfbf | 2014-06-06 22:14:45 +0600 | [diff] [blame] | 360 | There is also a factory function that can decorate undefined objects to |
| 361 | implement logging on failures: |
| 362 | |
| 363 | .. autofunction:: jinja2.make_logging_undefined |
| 364 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 365 | Undefined objects are created by calling :attr:`undefined`. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 366 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 367 | .. admonition:: Implementation |
| 368 | |
| 369 | :class:`Undefined` objects are implemented by overriding the special |
| 370 | `__underscore__` methods. For example the default :class:`Undefined` |
| 371 | class implements `__unicode__` in a way that it returns an empty |
| 372 | string, however `__int__` and others still fail with an exception. To |
| 373 | allow conversion to int by returning ``0`` you can implement your own:: |
| 374 | |
| 375 | class NullUndefined(Undefined): |
| 376 | def __int__(self): |
| 377 | return 0 |
| 378 | def __float__(self): |
| 379 | return 0.0 |
| 380 | |
| 381 | To disallow a method, just override it and raise |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 382 | :attr:`~Undefined._undefined_exception`. Because this is a very common |
| 383 | idom in undefined objects there is the helper method |
| 384 | :meth:`~Undefined._fail_with_undefined_error` that does the error raising |
| 385 | automatically. Here a class that works like the regular :class:`Undefined` |
| 386 | but chokes on iteration:: |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 387 | |
| 388 | class NonIterableUndefined(Undefined): |
| 389 | __iter__ = Undefined._fail_with_undefined_error |
| 390 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 391 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 392 | The Context |
| 393 | ----------- |
| 394 | |
| Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame] | 395 | .. autoclass:: jinja2.runtime.Context() |
| Armin Ronacher | f35e281 | 2008-05-06 16:04:10 +0200 | [diff] [blame] | 396 | :members: resolve, get_exported, get_all |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 397 | |
| 398 | .. attribute:: parent |
| 399 | |
| 400 | A dict of read only, global variables the template looks up. These |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 401 | can either come from another :class:`Context`, from the |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 402 | :attr:`Environment.globals` or :attr:`Template.globals` or points |
| 403 | to a dict created by combining the globals with the variables |
| 404 | passed to the render function. It must not be altered. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 405 | |
| 406 | .. attribute:: vars |
| 407 | |
| 408 | The template local variables. This list contains environment and |
| 409 | context functions from the :attr:`parent` scope as well as local |
| 410 | modifications and exported variables from the template. The template |
| 411 | will modify this dict during template evaluation but filters and |
| 412 | context functions are not allowed to modify it. |
| 413 | |
| 414 | .. attribute:: environment |
| 415 | |
| 416 | The environment that loaded the template. |
| 417 | |
| 418 | .. attribute:: exported_vars |
| 419 | |
| 420 | This set contains all the names the template exports. The values for |
| 421 | the names are in the :attr:`vars` dict. In order to get a copy of the |
| 422 | exported variables as dict, :meth:`get_exported` can be used. |
| 423 | |
| 424 | .. attribute:: name |
| 425 | |
| 426 | The load name of the template owning this context. |
| 427 | |
| 428 | .. attribute:: blocks |
| 429 | |
| 430 | A dict with the current mapping of blocks in the template. The keys |
| 431 | in this dict are the names of the blocks, and the values a list of |
| 432 | blocks registered. The last item in each list is the current active |
| 433 | block (latest in the inheritance chain). |
| 434 | |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 435 | .. attribute:: eval_ctx |
| 436 | |
| 437 | The current :ref:`eval-context`. |
| 438 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 439 | .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs) |
| 440 | |
| 441 | |
| 442 | .. admonition:: Implementation |
| 443 | |
| 444 | Context is immutable for the same reason Python's frame locals are |
| 445 | immutable inside functions. Both Jinja2 and Python are not using the |
| 446 | context / frame locals as data storage for variables but only as primary |
| 447 | data source. |
| 448 | |
| 449 | When a template accesses a variable the template does not define, Jinja2 |
| 450 | looks up the variable in the context, after that the variable is treated |
| 451 | as if it was defined in the template. |
| 452 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 453 | |
| Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 454 | .. _loaders: |
| 455 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 456 | Loaders |
| 457 | ------- |
| 458 | |
| 459 | Loaders are responsible for loading templates from a resource such as the |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 460 | file system. The environment will keep the compiled modules in memory like |
| 461 | Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in |
| 462 | size by default and templates are automatically reloaded. |
| Armin Ronacher | cda43df | 2008-05-03 17:10:05 +0200 | [diff] [blame] | 463 | All loaders are subclasses of :class:`BaseLoader`. If you want to create your |
| Armin Ronacher | cda43df | 2008-05-03 17:10:05 +0200 | [diff] [blame] | 464 | own loader, subclass :class:`BaseLoader` and override `get_source`. |
| 465 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 466 | .. autoclass:: jinja2.BaseLoader |
| Armin Ronacher | cda43df | 2008-05-03 17:10:05 +0200 | [diff] [blame] | 467 | :members: get_source, load |
| 468 | |
| 469 | Here a list of the builtin loaders Jinja2 provides: |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 470 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 471 | .. autoclass:: jinja2.FileSystemLoader |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 472 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 473 | .. autoclass:: jinja2.PackageLoader |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 474 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 475 | .. autoclass:: jinja2.DictLoader |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 476 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 477 | .. autoclass:: jinja2.FunctionLoader |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 478 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 479 | .. autoclass:: jinja2.PrefixLoader |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 480 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 481 | .. autoclass:: jinja2.ChoiceLoader |
| 482 | |
| Armin Ronacher | 4684498 | 2011-01-29 20:19:58 +0100 | [diff] [blame] | 483 | .. autoclass:: jinja2.ModuleLoader |
| 484 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 485 | |
| 486 | .. _bytecode-cache: |
| 487 | |
| 488 | Bytecode Cache |
| 489 | -------------- |
| 490 | |
| 491 | Jinja 2.1 and higher support external bytecode caching. Bytecode caches make |
| 492 | it possible to store the generated bytecode on the file system or a different |
| 493 | location to avoid parsing the templates on first use. |
| 494 | |
| 495 | This is especially useful if you have a web application that is initialized on |
| 496 | the first request and Jinja compiles many templates at once which slows down |
| 497 | the application. |
| 498 | |
| Jakub Wilk | 3fc008b | 2013-05-25 23:37:34 +0200 | [diff] [blame] | 499 | To use a bytecode cache, instantiate it and pass it to the :class:`Environment`. |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 500 | |
| 501 | .. autoclass:: jinja2.BytecodeCache |
| 502 | :members: load_bytecode, dump_bytecode, clear |
| 503 | |
| 504 | .. autoclass:: jinja2.bccache.Bucket |
| 505 | :members: write_bytecode, load_bytecode, bytecode_from_string, |
| 506 | bytecode_to_string, reset |
| 507 | |
| 508 | .. attribute:: environment |
| 509 | |
| 510 | The :class:`Environment` that created the bucket. |
| 511 | |
| 512 | .. attribute:: key |
| 513 | |
| 514 | The unique cache key for this bucket |
| 515 | |
| 516 | .. attribute:: code |
| 517 | |
| 518 | The bytecode if it's loaded, otherwise `None`. |
| 519 | |
| 520 | |
| 521 | Builtin bytecode caches: |
| 522 | |
| 523 | .. autoclass:: jinja2.FileSystemBytecodeCache |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 524 | |
| Armin Ronacher | aa1d17d | 2008-09-18 18:09:06 +0200 | [diff] [blame] | 525 | .. autoclass:: jinja2.MemcachedBytecodeCache |
| 526 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 527 | |
| Armin Ronacher | d8326d9 | 2016-12-28 22:51:46 +0100 | [diff] [blame] | 528 | Async Support |
| 529 | ------------- |
| 530 | |
| 531 | Starting with version 2.9, Jinja2 also supports the Python `async` and |
| 532 | `await` constructs. As far as template designers go this feature is |
| 533 | entirely opaque to them however as a developer you should be aware of how |
| 534 | it's implemented as it influences what type of APIs you can safely expose |
| 535 | to the template environment. |
| 536 | |
| 537 | First you need to be aware that by default async support is disabled as |
| 538 | enabling it will generate different template code behind the scenes which |
| 539 | passes everything through the asyncio event loop. This is important to |
| 540 | understand because it has some impact to what you are doing: |
| 541 | |
| 542 | * template rendering will require an event loop to be set for the |
| 543 | current thread (``asyncio.get_event_loop`` needs to return one) |
| 544 | * all template generation code internally runs async generators which |
| 545 | means that you will pay a performance penalty even if the non sync |
| 546 | methods are used! |
| 547 | * The sync methods are based on async methods if the async mode is |
| 548 | enabled which means that `render` for instance will internally invoke |
| 549 | `render_async` and run it as part of the current event loop until the |
| 550 | execution finished. |
| 551 | |
| 552 | Awaitable objects can be returned from functions in templates and any |
| 553 | function call in a template will automatically await the result. This |
| 554 | means that you can let provide a method that asynchronously loads data |
| 555 | from a database if you so desire and from the template designer's point of |
| 556 | view this is just another function they can call. This means that the |
| 557 | ``await`` you would normally issue in Python is implied. However this |
| 558 | only applies to function calls. If an attribute for instance would be an |
| 559 | avaitable object then this would not result in the expected behavior. |
| 560 | |
| 561 | Likewise iterations with a `for` loop support async iterators. |
| 562 | |
| Armin Ronacher | e253520 | 2016-12-31 00:43:50 +0100 | [diff] [blame] | 563 | .. _policies: |
| 564 | |
| 565 | Policies |
| 566 | -------- |
| 567 | |
| 568 | Starting with Jinja 2.9 policies can be configured on the environment |
| 569 | which can slightly influence how filters and other template constructs |
| 570 | behave. They can be configured with the |
| 571 | :attr:`~jinja2.Environment.policies` attribute. |
| 572 | |
| 573 | Example:: |
| 574 | |
| 575 | env.policies['urlize.rel'] = 'nofollow noopener' |
| 576 | |
| Armin Ronacher | 028f058 | 2017-01-07 14:57:44 +0100 | [diff] [blame] | 577 | ``compiler.ascii_str``: |
| 578 | This boolean controls on Python 2 if Jinja2 should store ASCII only |
| 579 | literals as bytestring instead of unicode strings. This used to be |
| 580 | always enabled for Jinja versions below 2.9 and now can be changed. |
| 581 | Traditionally it was done this way since some APIs in Python 2 failed |
| 582 | badly for unicode strings (for instance the datetime strftime API). |
| 583 | Now however sometimes the inverse is true (for instance str.format). |
| 584 | If this is set to False then all strings are stored as unicode |
| 585 | internally. |
| 586 | |
| Armin Ronacher | e253520 | 2016-12-31 00:43:50 +0100 | [diff] [blame] | 587 | ``urlize.rel``: |
| 588 | A string that defines the items for the `rel` attribute of generated |
| 589 | links with the `urlize` filter. These items are always added. The |
| 590 | default is `noopener`. |
| 591 | |
| 592 | ``urlize.target``: |
| 593 | The default target that is issued for links from the `urlize` filter |
| 594 | if no other target is defined by the call explicitly. |
| 595 | |
| Armin Ronacher | e71a130 | 2017-01-06 21:33:51 +0100 | [diff] [blame] | 596 | ``json.dumps_function``: |
| 597 | If this is set to a value other than `None` then the `tojson` filter |
| 598 | will dump with this function instead of the default one. Note that |
| 599 | this function should accept arbitrary extra arguments which might be |
| 600 | passed in the future from the filter. Currently the only argument |
| 601 | that might be passed is `indent`. The default dump function is |
| 602 | ``json.dumps``. |
| 603 | |
| 604 | ``json.dumps_kwargs``: |
| 605 | Keyword arguments to be passed to the dump function. The default is |
| 606 | ``{'sort_keys': True}``. |
| 607 | |
| Armin Ronacher | d8326d9 | 2016-12-28 22:51:46 +0100 | [diff] [blame] | 608 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 609 | Utilities |
| 610 | --------- |
| 611 | |
| 612 | These helper functions and classes are useful if you add custom filters or |
| 613 | functions to a Jinja2 environment. |
| 614 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 615 | .. autofunction:: jinja2.environmentfilter |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 616 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 617 | .. autofunction:: jinja2.contextfilter |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 618 | |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 619 | .. autofunction:: jinja2.evalcontextfilter |
| 620 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 621 | .. autofunction:: jinja2.environmentfunction |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 622 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 623 | .. autofunction:: jinja2.contextfunction |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 624 | |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 625 | .. autofunction:: jinja2.evalcontextfunction |
| 626 | |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 627 | .. function:: escape(s) |
| 628 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 629 | Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s` |
| 630 | to HTML-safe sequences. Use this if you need to display text that might |
| 631 | contain such characters in HTML. This function will not escaped objects |
| 632 | that do have an HTML representation such as already escaped data. |
| 633 | |
| 634 | The return value is a :class:`Markup` string. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 635 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 636 | .. autofunction:: jinja2.clear_caches |
| Armin Ronacher | 187bde1 | 2008-05-01 18:19:16 +0200 | [diff] [blame] | 637 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 638 | .. autofunction:: jinja2.is_undefined |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 639 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 640 | .. autoclass:: jinja2.Markup([string]) |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 641 | :members: escape, unescape, striptags |
| 642 | |
| 643 | .. admonition:: Note |
| 644 | |
| 645 | The Jinja2 :class:`Markup` class is compatible with at least Pylons and |
| 646 | Genshi. It's expected that more template engines and framework will pick |
| 647 | up the `__html__` concept soon. |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 648 | |
| 649 | |
| 650 | Exceptions |
| 651 | ---------- |
| 652 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 653 | .. autoexception:: jinja2.TemplateError |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 654 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 655 | .. autoexception:: jinja2.UndefinedError |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 656 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 657 | .. autoexception:: jinja2.TemplateNotFound |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 658 | |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 659 | .. autoexception:: jinja2.TemplatesNotFound |
| 660 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 661 | .. autoexception:: jinja2.TemplateSyntaxError |
| Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 662 | |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 663 | .. attribute:: message |
| 664 | |
| 665 | The error message as utf-8 bytestring. |
| 666 | |
| 667 | .. attribute:: lineno |
| 668 | |
| 669 | The line number where the error occurred |
| 670 | |
| 671 | .. attribute:: name |
| 672 | |
| 673 | The load name for the template as unicode string. |
| 674 | |
| 675 | .. attribute:: filename |
| 676 | |
| 677 | The filename that loaded the template as bytestring in the encoding |
| 678 | of the file system (most likely utf-8 or mbcs on Windows systems). |
| 679 | |
| 680 | The reason why the filename and error message are bytestrings and not |
| 681 | unicode strings is that Python 2.x is not using unicode for exceptions |
| 682 | and tracebacks as well as the compiler. This will change with Python 3. |
| 683 | |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 684 | .. autoexception:: jinja2.TemplateAssertionError |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 685 | |
| 686 | |
| 687 | .. _writing-filters: |
| 688 | |
| 689 | Custom Filters |
| 690 | -------------- |
| 691 | |
| 692 | Custom filters are just regular Python functions that take the left side of |
| Guillaume Paumier | 345e0ba | 2016-04-10 08:58:06 -0700 | [diff] [blame] | 693 | the filter as first argument and the arguments passed to the filter as |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 694 | extra arguments or keyword arguments. |
| 695 | |
| 696 | For example in the filter ``{{ 42|myfilter(23) }}`` the function would be |
| 697 | called with ``myfilter(42, 23)``. Here for example a simple filter that can |
| 698 | be applied to datetime objects to format them:: |
| 699 | |
| 700 | def datetimeformat(value, format='%H:%M / %d-%m-%Y'): |
| 701 | return value.strftime(format) |
| 702 | |
| 703 | You can register it on the template environment by updating the |
| 704 | :attr:`~Environment.filters` dict on the environment:: |
| 705 | |
| 706 | environment.filters['datetimeformat'] = datetimeformat |
| 707 | |
| 708 | Inside the template it can then be used as follows: |
| 709 | |
| 710 | .. sourcecode:: jinja |
| 711 | |
| 712 | written on: {{ article.pub_date|datetimeformat }} |
| 713 | publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} |
| 714 | |
| 715 | Filters can also be passed the current template context or environment. This |
| Armin Ronacher | 0aa0f58 | 2009-03-18 01:01:36 +0100 | [diff] [blame] | 716 | is useful if a filter wants to return an undefined value or check the current |
| Armin Ronacher | 2e3c9c7 | 2010-04-10 13:03:46 +0200 | [diff] [blame] | 717 | :attr:`~Environment.autoescape` setting. For this purpose three decorators |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 718 | exist: :func:`environmentfilter`, :func:`contextfilter` and |
| 719 | :func:`evalcontextfilter`. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 720 | |
| 721 | Here a small example filter that breaks a text into HTML line breaks and |
| 722 | paragraphs and marks the return value as safe HTML string if autoescaping is |
| 723 | enabled:: |
| 724 | |
| 725 | import re |
| Jeffrey Finkelstein | 449ef02 | 2011-07-01 15:46:54 -0700 | [diff] [blame] | 726 | from jinja2 import evalcontextfilter, Markup, escape |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 727 | |
| 728 | _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') |
| 729 | |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 730 | @evalcontextfilter |
| 731 | def nl2br(eval_ctx, value): |
| Jörn Hees | 1702451 | 2014-06-15 18:31:16 +0200 | [diff] [blame] | 732 | result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 733 | for p in _paragraph_re.split(escape(value))) |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 734 | if eval_ctx.autoescape: |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 735 | result = Markup(result) |
| 736 | return result |
| 737 | |
| 738 | Context filters work the same just that the first argument is the current |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 739 | active :class:`Context` rather then the environment. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 740 | |
| 741 | |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 742 | .. _eval-context: |
| 743 | |
| 744 | Evaluation Context |
| 745 | ------------------ |
| 746 | |
| 747 | The evaluation context (short eval context or eval ctx) is a new object |
| Jakub Wilk | 3fc008b | 2013-05-25 23:37:34 +0200 | [diff] [blame] | 748 | introduced in Jinja 2.4 that makes it possible to activate and deactivate |
| Armin Ronacher | fe150f3 | 2010-03-15 02:42:41 +0100 | [diff] [blame] | 749 | compiled features at runtime. |
| 750 | |
| 751 | Currently it is only used to enable and disable the automatic escaping but |
| 752 | can be used for extensions as well. |
| 753 | |
| 754 | In previous Jinja versions filters and functions were marked as |
| 755 | environment callables in order to check for the autoescape status from the |
| 756 | environment. In new versions it's encouraged to check the setting from the |
| 757 | evaluation context instead. |
| 758 | |
| 759 | Previous versions:: |
| 760 | |
| 761 | @environmentfilter |
| 762 | def filter(env, value): |
| 763 | result = do_something(value) |
| 764 | if env.autoescape: |
| 765 | result = Markup(result) |
| 766 | return result |
| 767 | |
| 768 | In new versions you can either use a :func:`contextfilter` and access the |
| 769 | evaluation context from the actual context, or use a |
| 770 | :func:`evalcontextfilter` which directly passes the evaluation context to |
| 771 | the function:: |
| 772 | |
| 773 | @contextfilter |
| 774 | def filter(context, value): |
| 775 | result = do_something(value) |
| 776 | if context.eval_ctx.autoescape: |
| 777 | result = Markup(result) |
| 778 | return result |
| 779 | |
| 780 | @evalcontextfilter |
| 781 | def filter(eval_ctx, value): |
| 782 | result = do_something(value) |
| 783 | if eval_ctx.autoescape: |
| 784 | result = Markup(result) |
| 785 | return result |
| 786 | |
| 787 | The evaluation context must not be modified at runtime. Modifications |
| 788 | must only happen with a :class:`nodes.EvalContextModifier` and |
| 789 | :class:`nodes.ScopedEvalContextModifier` from an extension, not on the |
| 790 | eval context object itself. |
| 791 | |
| Armin Ronacher | 76ae15e | 2010-03-15 09:36:47 +0100 | [diff] [blame] | 792 | .. autoclass:: jinja2.nodes.EvalContext |
| Armin Ronacher | 30fda27 | 2010-03-15 03:06:04 +0100 | [diff] [blame] | 793 | |
| 794 | .. attribute:: autoescape |
| 795 | |
| 796 | `True` or `False` depending on if autoescaping is active or not. |
| 797 | |
| 798 | .. attribute:: volatile |
| 799 | |
| 800 | `True` if the compiler cannot evaluate some expressions at compile |
| 801 | time. At runtime this should always be `False`. |
| 802 | |
| 803 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 804 | .. _writing-tests: |
| 805 | |
| 806 | Custom Tests |
| 807 | ------------ |
| 808 | |
| Armin Ronacher | a5d8f55 | 2008-09-11 20:46:34 +0200 | [diff] [blame] | 809 | Tests work like filters just that there is no way for a test to get access |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 810 | to the environment or context and that they can't be chained. The return |
| Armin Ronacher | a5d8f55 | 2008-09-11 20:46:34 +0200 | [diff] [blame] | 811 | value of a test should be `True` or `False`. The purpose of a test is to |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 812 | give the template designers the possibility to perform type and conformability |
| 813 | checks. |
| 814 | |
| Armin Ronacher | a5d8f55 | 2008-09-11 20:46:34 +0200 | [diff] [blame] | 815 | Here a simple test that checks if a variable is a prime number:: |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 816 | |
| 817 | import math |
| 818 | |
| 819 | def is_prime(n): |
| 820 | if n == 2: |
| 821 | return True |
| 822 | for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): |
| 823 | if n % i == 0: |
| 824 | return False |
| 825 | return True |
| 826 | |
| 827 | |
| 828 | You can register it on the template environment by updating the |
| 829 | :attr:`~Environment.tests` dict on the environment:: |
| 830 | |
| 831 | environment.tests['prime'] = is_prime |
| 832 | |
| 833 | A template designer can then use the test like this: |
| 834 | |
| 835 | .. sourcecode:: jinja |
| 836 | |
| 837 | {% if 42 is prime %} |
| 838 | 42 is a prime number |
| 839 | {% else %} |
| 840 | 42 is not a prime number |
| 841 | {% endif %} |
| 842 | |
| 843 | |
| 844 | .. _global-namespace: |
| 845 | |
| 846 | The Global Namespace |
| 847 | -------------------- |
| 848 | |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 849 | Variables stored in the :attr:`Environment.globals` dict are special as they |
| 850 | are available for imported templates too, even if they are imported without |
| 851 | context. This is the place where you can put variables and functions |
| 852 | that should be available all the time. Additionally :attr:`Template.globals` |
| 853 | exist that are variables available to a specific template that are available |
| 854 | to all :meth:`~Template.render` calls. |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 855 | |
| 856 | |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 857 | .. _low-level-api: |
| 858 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 859 | Low Level API |
| 860 | ------------- |
| 861 | |
| 862 | The low level API exposes functionality that can be useful to understand some |
| 863 | implementation details, debugging purposes or advanced :ref:`extension |
| Armin Ronacher | 61a5a24 | 2008-05-26 12:07:44 +0200 | [diff] [blame] | 864 | <jinja-extensions>` techniques. Unless you know exactly what you are doing we |
| 865 | don't recommend using any of those. |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 866 | |
| 867 | .. automethod:: Environment.lex |
| 868 | |
| 869 | .. automethod:: Environment.parse |
| 870 | |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 871 | .. automethod:: Environment.preprocess |
| 872 | |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 873 | .. automethod:: Template.new_context |
| 874 | |
| 875 | .. method:: Template.root_render_func(context) |
| 876 | |
| 877 | This is the low level render function. It's passed a :class:`Context` |
| 878 | that has to be created by :meth:`new_context` of the same template or |
| 879 | a compatible template. This render function is generated by the |
| 880 | compiler from the template code and returns a generator that yields |
| 881 | unicode strings. |
| 882 | |
| 883 | If an exception in the template code happens the template engine will |
| 884 | not rewrite the exception but pass through the original one. As a |
| 885 | matter of fact this function should only be called from within a |
| 886 | :meth:`render` / :meth:`generate` / :meth:`stream` call. |
| 887 | |
| 888 | .. attribute:: Template.blocks |
| 889 | |
| 890 | A dict of block render functions. Each of these functions works exactly |
| 891 | like the :meth:`root_render_func` with the same limitations. |
| 892 | |
| 893 | .. attribute:: Template.is_up_to_date |
| 894 | |
| 895 | This attribute is `False` if there is a newer version of the template |
| 896 | available, otherwise `True`. |
| Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 897 | |
| 898 | .. admonition:: Note |
| 899 | |
| Armin Ronacher | 58f351d | 2008-05-28 21:30:14 +0200 | [diff] [blame] | 900 | The low-level API is fragile. Future Jinja2 versions will try not to |
| 901 | change it in a backwards incompatible way but modifications in the Jinja2 |
| 902 | core may shine through. For example if Jinja2 introduces a new AST node |
| 903 | in later versions that may be returned by :meth:`~Environment.parse`. |
| Armin Ronacher | 63cf9b8 | 2009-07-26 10:33:36 +0200 | [diff] [blame] | 904 | |
| 905 | The Meta API |
| 906 | ------------ |
| 907 | |
| 908 | .. versionadded:: 2.2 |
| 909 | |
| 910 | The meta API returns some information about abstract syntax trees that |
| 911 | could help applications to implement more advanced template concepts. All |
| 912 | the functions of the meta API operate on an abstract syntax tree as |
| 913 | returned by the :meth:`Environment.parse` method. |
| 914 | |
| 915 | .. autofunction:: jinja2.meta.find_undeclared_variables |
| 916 | |
| 917 | .. autofunction:: jinja2.meta.find_referenced_templates |