nativetypes.rst
This file
Path
docs/nativetypes.rst
64 lines · 1.5 KiB
Last changed by
Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
History of this fileTake it
Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 1why, one step back1.. module:: jinja2.nativetypesMerge pull request #708 from jctanner/NATIVE_TYPESDavid Lordbefore adoptiond17c7db
lines 2–7why, one step back23.. _nativetypes:45Native Python Types6===================7Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 8why, one step back8The default :class:`~jinja2.Environment` renders templates to strings. WithMerge pull request #708 from jctanner/NATIVE_TYPESDavid Lordbefore adoptiond17c7db
lines 9–64why, one step back9: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)56155758API59---6061.. autoclass:: NativeEnvironment([options])6263.. autoclass:: NativeTemplate([options])64 :members: render