1.. module:: jinja2.nativetypes
2
3.. _nativetypes:
4
5Native Python Types
6===================
7
8The default :class:`~jinja2.Environment` renders templates to strings. With
9:class:`NativeEnvironment`, rendering a template produces a native Python type.
10This is useful if you are using Jinja outside the context of creating text
11files. For example, your code may have an intermediate step where users may use
12templates to define values that will then be passed to a traditional string
13environment.
14
15Examples
16--------
17
18Adding 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)
246
25>>> print(type(result))
26int
27
28Rendering 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))
35list
36
37Rendering 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)
424 * 2
43>>> print(type(result))
44str
45
46Rendering 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__)
54Foo
55>>> print(result.value)
5615
57
58API
59---
60
61.. autoclass:: NativeEnvironment([options])
62
63.. autoclass:: NativeTemplate([options])
64    :members: render
65