| 1 |
.. module:: jinja2.nativetypes |
| 2 |
|
| 3 |
.. _nativetypes: |
| 4 |
|
| 5 |
Native Python Types |
| 6 |
=================== |
| 7 |
|
| 8 |
The default :class:`~jinja2.Environment` renders templates to strings. With |
| 9 |
:class:`NativeEnvironment`, rendering a template produces a native Python type. |
| 10 |
This is useful if you are using Jinja outside the context of creating text |
| 11 |
files. For example, your code may have an intermediate step where users may use |
| 12 |
templates to define values that will then be passed to a traditional string |
| 13 |
environment. |
| 14 |
|
| 15 |
Examples |
| 16 |
-------- |
| 17 |
|
| 18 |
Adding two values results in an integer, not a string with a number: |
| 19 |
|
| 20 |
>>> env = NativeEnvironment() |
| 21 |
>>> t = env.from_string('{{ x + y }}') |
| 22 |
>>> result = t.render(x=4, y=2) |
| 23 |
>>> print(result) |
| 24 |
6 |
| 25 |
>>> print(type(result)) |
| 26 |
int |
| 27 |
|
| 28 |
Rendering list syntax produces a list: |
| 29 |
|
| 30 |
>>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]') |
| 31 |
>>> result = t.render(data=range(5)) |
| 32 |
>>> print(result) |
| 33 |
[1, 2, 3, 4, 5] |
| 34 |
>>> print(type(result)) |
| 35 |
list |
| 36 |
|
| 37 |
Rendering something that doesn't look like a Python literal produces a string: |
| 38 |
|
| 39 |
>>> t = env.from_string('{{ x }} * {{ y }}') |
| 40 |
>>> result = t.render(x=4, y=2) |
| 41 |
>>> print(result) |
| 42 |
4 * 2 |
| 43 |
>>> print(type(result)) |
| 44 |
str |
| 45 |
|
| 46 |
Rendering a Python object produces that object as long as it is the only node: |
| 47 |
|
| 48 |
>>> class Foo: |
| 49 |
... def __init__(self, value): |
| 50 |
... self.value = value |
| 51 |
... |
| 52 |
>>> result = env.from_string('{{ x }}').render(x=Foo(15)) |
| 53 |
>>> print(type(result).__name__) |
| 54 |
Foo |
| 55 |
>>> print(result.value) |
| 56 |
15 |
| 57 |
|
| 58 |
Sandboxed Native Environment |
| 59 |
---------------------------- |
| 60 |
|
| 61 |
You can combine :class:`.SandboxedEnvironment` and :class:`NativeEnvironment` to |
| 62 |
get both behaviors. |
| 63 |
|
| 64 |
.. code-block:: python |
| 65 |
|
| 66 |
class SandboxedNativeEnvironment(SandboxedEnvironment, NativeEnvironment): |
| 67 |
pass |
| 68 |
|
| 69 |
API |
| 70 |
--- |
| 71 |
|
| 72 |
.. autoclass:: NativeEnvironment([options]) |
| 73 |
|
| 74 |
.. autoclass:: NativeTemplate([options]) |
| 75 |
:members: render |