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`. |
| 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 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 50 | .. autoclass:: jinja2.environment.Environment([options]) |
Armin Ronacher | 762079c | 2008-05-08 23:57:56 +0200 | [diff] [blame] | 51 | :members: from_string, get_template, join_path, parse, lex, extend |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 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 |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 70 | 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] | 71 | see :ref:`writing-filters`. For valid filter names have a look at |
| 72 | :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 73 | |
| 74 | .. attribute:: tests |
| 75 | |
Lukas Meuser | ad48a2e | 2008-05-01 18:19:57 +0200 | [diff] [blame] | 76 | A dict of test functions for this environment. As long as no |
| 77 | 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] | 78 | see :ref:`writing-tests`. For valid test names have a look at |
| 79 | :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 80 | |
| 81 | .. attribute:: globals |
| 82 | |
| 83 | A dict of global variables. These variables are always available |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 84 | 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] | 85 | to modify this dict. For more details see :ref:`global-namespace`. |
Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 86 | For valid object names have a look at :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 87 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 88 | .. automethod:: overlay([options]) |
| 89 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 90 | |
| 91 | .. autoclass:: jinja2.Template |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 92 | :members: make_module, module, new_context |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 93 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 94 | .. attribute:: globals |
| 95 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 96 | The dict with the globals of that template. It's unsafe to modify |
| 97 | this dict as it may be shared with other templates or the environment |
| 98 | that loaded the template. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 99 | |
| 100 | .. attribute:: name |
| 101 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 102 | The loading name of the template. If the template was loaded from a |
| 103 | string this is `None`. |
| 104 | |
| 105 | .. automethod:: render([context]) |
| 106 | |
| 107 | .. automethod:: generate([context]) |
| 108 | |
| 109 | .. automethod:: stream([context]) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 110 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 111 | |
Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame^] | 112 | .. autoclass:: jinja2.environment.TemplateStream() |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 113 | :members: disable_buffering, enable_buffering |
| 114 | |
| 115 | |
Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 116 | .. _identifier-naming: |
| 117 | |
| 118 | Notes on Identifiers |
| 119 | ~~~~~~~~~~~~~~~~~~~~ |
| 120 | |
| 121 | Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to |
| 122 | match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters |
| 123 | are currently not allowed. This limitation will probably go away as soon as |
| 124 | unicode identifiers are fully specified for Python 3. |
| 125 | |
| 126 | Filters and tests are looked up in separate namespaces and have slightly |
| 127 | modified identifier syntax. Filters and tests may contain dots to group |
| 128 | filters and tests by topic. For example it's perfectly valid to add a |
| 129 | function into the filter dict and call it `to.unicode`. The regular |
| 130 | expression for filter and test identifiers is |
| 131 | ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. |
| 132 | |
| 133 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 134 | Undefined Types |
| 135 | --------------- |
| 136 | |
| 137 | These classes can be used as undefined types. The :class:`Environment` |
| 138 | constructor takes an `undefined` parameter that can be one of those classes |
| 139 | or a custom subclass of :class:`Undefined`. Whenever the template engine is |
| 140 | unable to look up a name or access an attribute one of those objects is |
| 141 | created and returned. Some operations on undefined values are then allowed, |
| 142 | others fail. |
| 143 | |
| 144 | The closest to regular Python behavior is the `StrictUndefined` which |
| 145 | disallows all operations beside testing if it's an undefined object. |
| 146 | |
| 147 | .. autoclass:: jinja2.runtime.Undefined |
| 148 | |
| 149 | .. autoclass:: jinja2.runtime.DebugUndefined |
| 150 | |
| 151 | .. autoclass:: jinja2.runtime.StrictUndefined |
| 152 | |
| 153 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 154 | The Context |
| 155 | ----------- |
| 156 | |
Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame^] | 157 | .. autoclass:: jinja2.runtime.Context() |
Armin Ronacher | f35e281 | 2008-05-06 16:04:10 +0200 | [diff] [blame] | 158 | :members: resolve, get_exported, get_all |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 159 | |
| 160 | .. attribute:: parent |
| 161 | |
| 162 | A dict of read only, global variables the template looks up. These |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 163 | can either come from another :class:`Context`, from the |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 164 | :attr:`Environment.globals` or :attr:`Template.globals`. It must not |
| 165 | be altered. |
| 166 | |
| 167 | .. attribute:: vars |
| 168 | |
| 169 | The template local variables. This list contains environment and |
| 170 | context functions from the :attr:`parent` scope as well as local |
| 171 | modifications and exported variables from the template. The template |
| 172 | will modify this dict during template evaluation but filters and |
| 173 | context functions are not allowed to modify it. |
| 174 | |
| 175 | .. attribute:: environment |
| 176 | |
| 177 | The environment that loaded the template. |
| 178 | |
| 179 | .. attribute:: exported_vars |
| 180 | |
| 181 | This set contains all the names the template exports. The values for |
| 182 | the names are in the :attr:`vars` dict. In order to get a copy of the |
| 183 | exported variables as dict, :meth:`get_exported` can be used. |
| 184 | |
| 185 | .. attribute:: name |
| 186 | |
| 187 | The load name of the template owning this context. |
| 188 | |
| 189 | .. attribute:: blocks |
| 190 | |
| 191 | A dict with the current mapping of blocks in the template. The keys |
| 192 | in this dict are the names of the blocks, and the values a list of |
| 193 | blocks registered. The last item in each list is the current active |
| 194 | block (latest in the inheritance chain). |
| 195 | |
| 196 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 197 | .. _loaders: |
| 198 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 199 | Loaders |
| 200 | ------- |
| 201 | |
| 202 | Loaders are responsible for loading templates from a resource such as the |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 203 | file system. The environment will keep the compiled modules in memory like |
| 204 | Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in |
| 205 | size by default and templates are automatically reloaded. |
Armin Ronacher | cda43df | 2008-05-03 17:10:05 +0200 | [diff] [blame] | 206 | 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] | 207 | own loader, subclass :class:`BaseLoader` and override `get_source`. |
| 208 | |
| 209 | .. autoclass:: jinja2.loaders.BaseLoader |
| 210 | :members: get_source, load |
| 211 | |
| 212 | Here a list of the builtin loaders Jinja2 provides: |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 213 | |
| 214 | .. autoclass:: jinja2.loaders.FileSystemLoader |
| 215 | |
| 216 | .. autoclass:: jinja2.loaders.PackageLoader |
| 217 | |
| 218 | .. autoclass:: jinja2.loaders.DictLoader |
| 219 | |
| 220 | .. autoclass:: jinja2.loaders.FunctionLoader |
| 221 | |
| 222 | .. autoclass:: jinja2.loaders.PrefixLoader |
| 223 | |
| 224 | .. autoclass:: jinja2.loaders.ChoiceLoader |
| 225 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 226 | |
| 227 | Utilities |
| 228 | --------- |
| 229 | |
| 230 | These helper functions and classes are useful if you add custom filters or |
| 231 | functions to a Jinja2 environment. |
| 232 | |
| 233 | .. autofunction:: jinja2.filters.environmentfilter |
| 234 | |
| 235 | .. autofunction:: jinja2.filters.contextfilter |
| 236 | |
| 237 | .. autofunction:: jinja2.utils.environmentfunction |
| 238 | |
| 239 | .. autofunction:: jinja2.utils.contextfunction |
| 240 | |
| 241 | .. function:: escape(s) |
| 242 | |
| 243 | Convert the characters &, <, >, and " in string s to HTML-safe sequences. |
| 244 | Use this if you need to display text that might contain such characters |
| 245 | in HTML. This function will not escaped objects that do have an HTML |
| 246 | representation such as already escaped data. |
| 247 | |
Armin Ronacher | 187bde1 | 2008-05-01 18:19:16 +0200 | [diff] [blame] | 248 | .. autofunction:: jinja2.utils.clear_caches |
| 249 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 250 | .. autoclass:: jinja2.utils.Markup |
| 251 | |
| 252 | |
| 253 | Exceptions |
| 254 | ---------- |
| 255 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 256 | .. autoexception:: jinja2.exceptions.TemplateError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 257 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 258 | .. autoexception:: jinja2.exceptions.UndefinedError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 259 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 260 | .. autoexception:: jinja2.exceptions.TemplateNotFound |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 261 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 262 | .. autoexception:: jinja2.exceptions.TemplateSyntaxError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 263 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 264 | .. autoexception:: jinja2.exceptions.TemplateAssertionError |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 265 | |
| 266 | |
| 267 | .. _writing-filters: |
| 268 | |
| 269 | Custom Filters |
| 270 | -------------- |
| 271 | |
| 272 | Custom filters are just regular Python functions that take the left side of |
| 273 | the filter as first argument and the the arguments passed to the filter as |
| 274 | extra arguments or keyword arguments. |
| 275 | |
| 276 | For example in the filter ``{{ 42|myfilter(23) }}`` the function would be |
| 277 | called with ``myfilter(42, 23)``. Here for example a simple filter that can |
| 278 | be applied to datetime objects to format them:: |
| 279 | |
| 280 | def datetimeformat(value, format='%H:%M / %d-%m-%Y'): |
| 281 | return value.strftime(format) |
| 282 | |
| 283 | You can register it on the template environment by updating the |
| 284 | :attr:`~Environment.filters` dict on the environment:: |
| 285 | |
| 286 | environment.filters['datetimeformat'] = datetimeformat |
| 287 | |
| 288 | Inside the template it can then be used as follows: |
| 289 | |
| 290 | .. sourcecode:: jinja |
| 291 | |
| 292 | written on: {{ article.pub_date|datetimeformat }} |
| 293 | publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} |
| 294 | |
| 295 | Filters can also be passed the current template context or environment. This |
| 296 | is useful if a filters wants to return an undefined value or check the current |
| 297 | :attr:`~Environment.autoescape` setting. For this purpose two decorators |
| 298 | exist: :func:`environmentfilter` and :func:`contextfilter`. |
| 299 | |
| 300 | Here a small example filter that breaks a text into HTML line breaks and |
| 301 | paragraphs and marks the return value as safe HTML string if autoescaping is |
| 302 | enabled:: |
| 303 | |
| 304 | import re |
| 305 | from jinja2 import environmentfilter, Markup, escape |
| 306 | |
| 307 | _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') |
| 308 | |
| 309 | @environmentfilter |
| 310 | def nl2br(environment, value): |
| 311 | result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') |
| 312 | for p in _paragraph_re.split(escape(value))) |
| 313 | if environment.autoescape: |
| 314 | result = Markup(result) |
| 315 | return result |
| 316 | |
| 317 | 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] | 318 | active :class:`Context` rather then the environment. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 319 | |
| 320 | |
| 321 | .. _writing-tests: |
| 322 | |
| 323 | Custom Tests |
| 324 | ------------ |
| 325 | |
| 326 | Tests work like filters just that there is no way for a filter to get access |
| 327 | to the environment or context and that they can't be chained. The return |
| 328 | value of a filter should be `True` or `False`. The purpose of a filter is to |
| 329 | give the template designers the possibility to perform type and conformability |
| 330 | checks. |
| 331 | |
| 332 | Here a simple filter that checks if a variable is a prime number:: |
| 333 | |
| 334 | import math |
| 335 | |
| 336 | def is_prime(n): |
| 337 | if n == 2: |
| 338 | return True |
| 339 | for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): |
| 340 | if n % i == 0: |
| 341 | return False |
| 342 | return True |
| 343 | |
| 344 | |
| 345 | You can register it on the template environment by updating the |
| 346 | :attr:`~Environment.tests` dict on the environment:: |
| 347 | |
| 348 | environment.tests['prime'] = is_prime |
| 349 | |
| 350 | A template designer can then use the test like this: |
| 351 | |
| 352 | .. sourcecode:: jinja |
| 353 | |
| 354 | {% if 42 is prime %} |
| 355 | 42 is a prime number |
| 356 | {% else %} |
| 357 | 42 is not a prime number |
| 358 | {% endif %} |
| 359 | |
| 360 | |
| 361 | .. _global-namespace: |
| 362 | |
| 363 | The Global Namespace |
| 364 | -------------------- |
| 365 | |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 366 | Variables stored in the :attr:`Environment.globals` dict are special as they |
| 367 | are available for imported templates too, even if they are imported without |
| 368 | context. This is the place where you can put variables and functions |
| 369 | that should be available all the time. Additionally :attr:`Template.globals` |
| 370 | exist that are variables available to a specific template that are available |
| 371 | to all :meth:`~Template.render` calls. |