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 | |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 47 | Unicode |
| 48 | ------- |
| 49 | |
| 50 | Jinja2 is using unicode internally which means that you have to pass unicode |
| 51 | objects to the render function or bytestrings that only consist of ASCII |
| 52 | characters. Additionally newlines are normalized to one end of line |
| 53 | sequence which is per default UNIX style (``\n``). |
| 54 | |
| 55 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 56 | High Level API |
| 57 | -------------- |
| 58 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 59 | .. autoclass:: Environment([options]) |
| 60 | :members: from_string, get_template, join_path, extend |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 61 | |
| 62 | .. attribute:: shared |
| 63 | |
| 64 | If a template was created by using the :class:`Template` constructor |
| 65 | an environment is created automatically. These environments are |
| 66 | created as shared environments which means that multiple templates |
| 67 | may have the same anonymous environment. For all shared environments |
| 68 | this attribute is `True`, else `False`. |
| 69 | |
| 70 | .. attribute:: sandboxed |
| 71 | |
| 72 | If the environment is sandboxed this attribute is `True`. For the |
| 73 | sandbox mode have a look at the documentation for the |
| 74 | :class:`~jinja2.sandbox.SandboxedEnvironment`. |
| 75 | |
| 76 | .. attribute:: filters |
| 77 | |
| 78 | 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] | 79 | 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] | 80 | see :ref:`writing-filters`. For valid filter names have a look at |
| 81 | :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 82 | |
| 83 | .. attribute:: tests |
| 84 | |
Lukas Meuser | ad48a2e | 2008-05-01 18:19:57 +0200 | [diff] [blame] | 85 | A dict of test functions for this environment. As long as no |
| 86 | 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] | 87 | see :ref:`writing-tests`. For valid test names have a look at |
| 88 | :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 89 | |
| 90 | .. attribute:: globals |
| 91 | |
| 92 | A dict of global variables. These variables are always available |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 93 | 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] | 94 | to modify this dict. For more details see :ref:`global-namespace`. |
Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 95 | For valid object names have a look at :ref:`identifier-naming`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 96 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 97 | .. automethod:: overlay([options]) |
| 98 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 99 | .. method:: undefined([hint,] [obj,] name[, exc]) |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 100 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 101 | Creates a new :class:`Undefined` object for `name`. This is useful |
| 102 | for filters or functions that may return undefined objects for |
| 103 | some operations. All parameters except of `hint` should be provided |
| 104 | as keyword parameters for better readability. The `hint` is used as |
| 105 | error message for the exception if provided, otherwise the error |
| 106 | message generated from `obj` and `name` automatically. The exception |
| 107 | provided as `exc` is raised if something with the generated undefined |
| 108 | object is done that the undefined object does not allow. The default |
| 109 | exception is :exc:`UndefinedError`. If a `hint` is provided the |
| 110 | `name` may be ommited. |
| 111 | |
| 112 | The most common way to create an undefined object is by providing |
| 113 | a name only:: |
| 114 | |
| 115 | return environment.undefined(name='some_name') |
| 116 | |
| 117 | This means that the name `some_name` is not defined. If the name |
| 118 | was from an attribute of an object it makes sense to tell the |
| 119 | undefined object the holder object to improve the error message:: |
| 120 | |
| 121 | if not hasattr(obj, 'attr'): |
| 122 | return environment.undefined(obj=obj, name='attr') |
| 123 | |
| 124 | For a more complex example you can provide a hint. For example |
| 125 | the :func:`first` filter creates an undefined object that way:: |
| 126 | |
| 127 | return environment.undefined('no first item, sequence was empty') |
| 128 | |
| 129 | If it the `name` or `obj` is known (for example because an attribute |
| 130 | was accessed) it shold be passed to the undefined object, even if |
| 131 | a custom `hint` is provided. This gives undefined objects the |
| 132 | possibility to enhance the error message. |
| 133 | |
| 134 | .. autoclass:: Template |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 135 | :members: make_module, module, new_context |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 136 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 137 | .. attribute:: globals |
| 138 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 139 | The dict with the globals of that template. It's unsafe to modify |
| 140 | this dict as it may be shared with other templates or the environment |
| 141 | that loaded the template. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 142 | |
| 143 | .. attribute:: name |
| 144 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 145 | The loading name of the template. If the template was loaded from a |
| 146 | string this is `None`. |
| 147 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 148 | .. attribute:: filename |
| 149 | |
| 150 | The filename of the template on the file system if it was loaded from |
| 151 | there. Otherwise this is `None`. |
| 152 | |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 153 | .. automethod:: render([context]) |
| 154 | |
| 155 | .. automethod:: generate([context]) |
| 156 | |
| 157 | .. automethod:: stream([context]) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 158 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 159 | |
Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame] | 160 | .. autoclass:: jinja2.environment.TemplateStream() |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 161 | :members: disable_buffering, enable_buffering |
| 162 | |
| 163 | |
Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 164 | .. _identifier-naming: |
| 165 | |
| 166 | Notes on Identifiers |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 167 | -------------------- |
Armin Ronacher | d1ff858 | 2008-05-11 00:30:43 +0200 | [diff] [blame] | 168 | |
| 169 | Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to |
| 170 | match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters |
| 171 | are currently not allowed. This limitation will probably go away as soon as |
| 172 | unicode identifiers are fully specified for Python 3. |
| 173 | |
| 174 | Filters and tests are looked up in separate namespaces and have slightly |
| 175 | modified identifier syntax. Filters and tests may contain dots to group |
| 176 | filters and tests by topic. For example it's perfectly valid to add a |
| 177 | function into the filter dict and call it `to.unicode`. The regular |
| 178 | expression for filter and test identifiers is |
| 179 | ``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. |
| 180 | |
| 181 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 182 | Undefined Types |
| 183 | --------------- |
| 184 | |
| 185 | These classes can be used as undefined types. The :class:`Environment` |
| 186 | constructor takes an `undefined` parameter that can be one of those classes |
| 187 | or a custom subclass of :class:`Undefined`. Whenever the template engine is |
| 188 | unable to look up a name or access an attribute one of those objects is |
| 189 | created and returned. Some operations on undefined values are then allowed, |
| 190 | others fail. |
| 191 | |
| 192 | The closest to regular Python behavior is the `StrictUndefined` which |
| 193 | disallows all operations beside testing if it's an undefined object. |
| 194 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 195 | .. autoclass:: jinja2.runtime.Undefined() |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 196 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 197 | .. autoclass:: jinja2.runtime.DebugUndefined() |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 198 | |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 199 | .. autoclass:: jinja2.runtime.StrictUndefined() |
| 200 | |
| 201 | Undefined objects are created by calling :attr:`undefined`. |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 202 | |
| 203 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 204 | The Context |
| 205 | ----------- |
| 206 | |
Armin Ronacher | 6df604e | 2008-05-23 22:18:38 +0200 | [diff] [blame] | 207 | .. autoclass:: jinja2.runtime.Context() |
Armin Ronacher | f35e281 | 2008-05-06 16:04:10 +0200 | [diff] [blame] | 208 | :members: resolve, get_exported, get_all |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 209 | |
| 210 | .. attribute:: parent |
| 211 | |
| 212 | A dict of read only, global variables the template looks up. These |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 213 | can either come from another :class:`Context`, from the |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 214 | :attr:`Environment.globals` or :attr:`Template.globals` or points |
| 215 | to a dict created by combining the globals with the variables |
| 216 | passed to the render function. It must not be altered. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 217 | |
| 218 | .. attribute:: vars |
| 219 | |
| 220 | The template local variables. This list contains environment and |
| 221 | context functions from the :attr:`parent` scope as well as local |
| 222 | modifications and exported variables from the template. The template |
| 223 | will modify this dict during template evaluation but filters and |
| 224 | context functions are not allowed to modify it. |
| 225 | |
| 226 | .. attribute:: environment |
| 227 | |
| 228 | The environment that loaded the template. |
| 229 | |
| 230 | .. attribute:: exported_vars |
| 231 | |
| 232 | This set contains all the names the template exports. The values for |
| 233 | the names are in the :attr:`vars` dict. In order to get a copy of the |
| 234 | exported variables as dict, :meth:`get_exported` can be used. |
| 235 | |
| 236 | .. attribute:: name |
| 237 | |
| 238 | The load name of the template owning this context. |
| 239 | |
| 240 | .. attribute:: blocks |
| 241 | |
| 242 | A dict with the current mapping of blocks in the template. The keys |
| 243 | in this dict are the names of the blocks, and the values a list of |
| 244 | blocks registered. The last item in each list is the current active |
| 245 | block (latest in the inheritance chain). |
| 246 | |
| 247 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 248 | .. _loaders: |
| 249 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 250 | Loaders |
| 251 | ------- |
| 252 | |
| 253 | Loaders are responsible for loading templates from a resource such as the |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 254 | file system. The environment will keep the compiled modules in memory like |
| 255 | Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in |
| 256 | size by default and templates are automatically reloaded. |
Armin Ronacher | cda43df | 2008-05-03 17:10:05 +0200 | [diff] [blame] | 257 | 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] | 258 | own loader, subclass :class:`BaseLoader` and override `get_source`. |
| 259 | |
| 260 | .. autoclass:: jinja2.loaders.BaseLoader |
| 261 | :members: get_source, load |
| 262 | |
| 263 | Here a list of the builtin loaders Jinja2 provides: |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 264 | |
| 265 | .. autoclass:: jinja2.loaders.FileSystemLoader |
| 266 | |
| 267 | .. autoclass:: jinja2.loaders.PackageLoader |
| 268 | |
| 269 | .. autoclass:: jinja2.loaders.DictLoader |
| 270 | |
| 271 | .. autoclass:: jinja2.loaders.FunctionLoader |
| 272 | |
| 273 | .. autoclass:: jinja2.loaders.PrefixLoader |
| 274 | |
| 275 | .. autoclass:: jinja2.loaders.ChoiceLoader |
| 276 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 277 | |
| 278 | Utilities |
| 279 | --------- |
| 280 | |
| 281 | These helper functions and classes are useful if you add custom filters or |
| 282 | functions to a Jinja2 environment. |
| 283 | |
| 284 | .. autofunction:: jinja2.filters.environmentfilter |
| 285 | |
| 286 | .. autofunction:: jinja2.filters.contextfilter |
| 287 | |
| 288 | .. autofunction:: jinja2.utils.environmentfunction |
| 289 | |
| 290 | .. autofunction:: jinja2.utils.contextfunction |
| 291 | |
| 292 | .. function:: escape(s) |
| 293 | |
| 294 | Convert the characters &, <, >, and " in string s to HTML-safe sequences. |
| 295 | Use this if you need to display text that might contain such characters |
| 296 | in HTML. This function will not escaped objects that do have an HTML |
| 297 | representation such as already escaped data. |
| 298 | |
Armin Ronacher | 187bde1 | 2008-05-01 18:19:16 +0200 | [diff] [blame] | 299 | .. autofunction:: jinja2.utils.clear_caches |
| 300 | |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 301 | .. autoclass:: jinja2.utils.Markup |
| 302 | |
| 303 | |
| 304 | Exceptions |
| 305 | ---------- |
| 306 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 307 | .. autoexception:: jinja2.exceptions.TemplateError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 308 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 309 | .. autoexception:: jinja2.exceptions.UndefinedError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 310 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 311 | .. autoexception:: jinja2.exceptions.TemplateNotFound |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 312 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 313 | .. autoexception:: jinja2.exceptions.TemplateSyntaxError |
Armin Ronacher | 3c8b7ad | 2008-04-28 13:52:21 +0200 | [diff] [blame] | 314 | |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 315 | .. attribute:: message |
| 316 | |
| 317 | The error message as utf-8 bytestring. |
| 318 | |
| 319 | .. attribute:: lineno |
| 320 | |
| 321 | The line number where the error occurred |
| 322 | |
| 323 | .. attribute:: name |
| 324 | |
| 325 | The load name for the template as unicode string. |
| 326 | |
| 327 | .. attribute:: filename |
| 328 | |
| 329 | The filename that loaded the template as bytestring in the encoding |
| 330 | of the file system (most likely utf-8 or mbcs on Windows systems). |
| 331 | |
| 332 | The reason why the filename and error message are bytestrings and not |
| 333 | unicode strings is that Python 2.x is not using unicode for exceptions |
| 334 | and tracebacks as well as the compiler. This will change with Python 3. |
| 335 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 336 | .. autoexception:: jinja2.exceptions.TemplateAssertionError |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 337 | |
| 338 | |
| 339 | .. _writing-filters: |
| 340 | |
| 341 | Custom Filters |
| 342 | -------------- |
| 343 | |
| 344 | Custom filters are just regular Python functions that take the left side of |
| 345 | the filter as first argument and the the arguments passed to the filter as |
| 346 | extra arguments or keyword arguments. |
| 347 | |
| 348 | For example in the filter ``{{ 42|myfilter(23) }}`` the function would be |
| 349 | called with ``myfilter(42, 23)``. Here for example a simple filter that can |
| 350 | be applied to datetime objects to format them:: |
| 351 | |
| 352 | def datetimeformat(value, format='%H:%M / %d-%m-%Y'): |
| 353 | return value.strftime(format) |
| 354 | |
| 355 | You can register it on the template environment by updating the |
| 356 | :attr:`~Environment.filters` dict on the environment:: |
| 357 | |
| 358 | environment.filters['datetimeformat'] = datetimeformat |
| 359 | |
| 360 | Inside the template it can then be used as follows: |
| 361 | |
| 362 | .. sourcecode:: jinja |
| 363 | |
| 364 | written on: {{ article.pub_date|datetimeformat }} |
| 365 | publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} |
| 366 | |
| 367 | Filters can also be passed the current template context or environment. This |
| 368 | is useful if a filters wants to return an undefined value or check the current |
| 369 | :attr:`~Environment.autoescape` setting. For this purpose two decorators |
| 370 | exist: :func:`environmentfilter` and :func:`contextfilter`. |
| 371 | |
| 372 | Here a small example filter that breaks a text into HTML line breaks and |
| 373 | paragraphs and marks the return value as safe HTML string if autoescaping is |
| 374 | enabled:: |
| 375 | |
| 376 | import re |
| 377 | from jinja2 import environmentfilter, Markup, escape |
| 378 | |
| 379 | _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') |
| 380 | |
| 381 | @environmentfilter |
| 382 | def nl2br(environment, value): |
| 383 | result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') |
| 384 | for p in _paragraph_re.split(escape(value))) |
| 385 | if environment.autoescape: |
| 386 | result = Markup(result) |
| 387 | return result |
| 388 | |
| 389 | 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] | 390 | active :class:`Context` rather then the environment. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 391 | |
| 392 | |
| 393 | .. _writing-tests: |
| 394 | |
| 395 | Custom Tests |
| 396 | ------------ |
| 397 | |
| 398 | Tests work like filters just that there is no way for a filter to get access |
| 399 | to the environment or context and that they can't be chained. The return |
| 400 | value of a filter should be `True` or `False`. The purpose of a filter is to |
| 401 | give the template designers the possibility to perform type and conformability |
| 402 | checks. |
| 403 | |
| 404 | Here a simple filter that checks if a variable is a prime number:: |
| 405 | |
| 406 | import math |
| 407 | |
| 408 | def is_prime(n): |
| 409 | if n == 2: |
| 410 | return True |
| 411 | for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): |
| 412 | if n % i == 0: |
| 413 | return False |
| 414 | return True |
| 415 | |
| 416 | |
| 417 | You can register it on the template environment by updating the |
| 418 | :attr:`~Environment.tests` dict on the environment:: |
| 419 | |
| 420 | environment.tests['prime'] = is_prime |
| 421 | |
| 422 | A template designer can then use the test like this: |
| 423 | |
| 424 | .. sourcecode:: jinja |
| 425 | |
| 426 | {% if 42 is prime %} |
| 427 | 42 is a prime number |
| 428 | {% else %} |
| 429 | 42 is not a prime number |
| 430 | {% endif %} |
| 431 | |
| 432 | |
| 433 | .. _global-namespace: |
| 434 | |
| 435 | The Global Namespace |
| 436 | -------------------- |
| 437 | |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 438 | Variables stored in the :attr:`Environment.globals` dict are special as they |
| 439 | are available for imported templates too, even if they are imported without |
| 440 | context. This is the place where you can put variables and functions |
| 441 | that should be available all the time. Additionally :attr:`Template.globals` |
| 442 | exist that are variables available to a specific template that are available |
| 443 | to all :meth:`~Template.render` calls. |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame^] | 444 | |
| 445 | |
| 446 | Low Level API |
| 447 | ------------- |
| 448 | |
| 449 | The low level API exposes functionality that can be useful to understand some |
| 450 | implementation details, debugging purposes or advanced :ref:`extension |
| 451 | <jinja-extensions>` techniques. |
| 452 | |
| 453 | .. automethod:: Environment.lex |
| 454 | |
| 455 | .. automethod:: Environment.parse |
| 456 | |
| 457 | .. automethod:: Template.new_context |
| 458 | |
| 459 | .. method:: Template.root_render_func(context) |
| 460 | |
| 461 | This is the low level render function. It's passed a :class:`Context` |
| 462 | that has to be created by :meth:`new_context` of the same template or |
| 463 | a compatible template. This render function is generated by the |
| 464 | compiler from the template code and returns a generator that yields |
| 465 | unicode strings. |
| 466 | |
| 467 | If an exception in the template code happens the template engine will |
| 468 | not rewrite the exception but pass through the original one. As a |
| 469 | matter of fact this function should only be called from within a |
| 470 | :meth:`render` / :meth:`generate` / :meth:`stream` call. |
| 471 | |
| 472 | .. attribute:: Template.blocks |
| 473 | |
| 474 | A dict of block render functions. Each of these functions works exactly |
| 475 | like the :meth:`root_render_func` with the same limitations. |
| 476 | |
| 477 | .. attribute:: Template.is_up_to_date |
| 478 | |
| 479 | This attribute is `False` if there is a newer version of the template |
| 480 | available, otherwise `True`. |