Skip to content
Myr

nativetypes.rst

This file

Path

docs/nativetypes.rst

75 lines · 1.8 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption6aeab5d

History of this file

Take it

The walk stopped after 200 commits: lines older than c580dd0 point at it.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1–57why, one step back
1.. module:: jinja2.nativetypes
23.. _nativetypes:45Native Python Types6===================78The default :class:`~jinja2.Environment` renders templates to strings. With9:class:`NativeEnvironment`, rendering a template produces a native Python type.10This is useful if you are using Jinja outside the context of creating text11files. For example, your code may have an intermediate step where users may use12templates to define values that will then be passed to a traditional string13environment.1415Examples16--------1718Adding two values results in an integer, not a string with a number:1920>>> env = NativeEnvironment()21>>> t = env.from_string('{{ x + y }}')22>>> result = t.render(x=4, y=2)23>>> print(result)24625>>> print(type(result))26int2728Rendering list syntax produces a list:2930>>> 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))35list3637Rendering something that doesn't look like a Python literal produces a string:3839>>> t = env.from_string('{{ x }} * {{ y }}')40>>> result = t.render(x=4, y=2)41>>> print(result)424 * 243>>> print(type(result))44str4546Rendering a Python object produces that object as long as it is the only node:4748>>> class Foo:49... def __init__(self, value):50... self.value = value51...52>>> result = env.from_string('{{ x }}').render(x=Foo(15))53>>> print(type(result).__name__)54Foo55>>> print(result.value)561557

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 58–68why, one step back
58Sandboxed Native Environment
59----------------------------6061You can combine :class:`.SandboxedEnvironment` and :class:`NativeEnvironment` to62get both behaviors.6364.. code-block:: python6566 class SandboxedNativeEnvironment(SandboxedEnvironment, NativeEnvironment):67 pass68

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 69–75why, one step back
69API
70---7172.. autoclass:: NativeEnvironment([options])7374.. autoclass:: NativeTemplate([options])75 :members: render