Native Python Types¶

The default Environment renders templates to strings. WithNativeEnvironment, rendering a template produces a native Python type.This is useful if you are using Jinja outside the context of creating textfiles. For example, your code may have an intermediate step where users may usetemplates to define values that will then be passed to a traditional stringenvironment.

Examples¶

Adding two values results in an integer, not a string with a number:

  1. >>> env = NativeEnvironment()
  2. >>> t = env.from_string('{{ x + y }}')
  3. >>> result = t.render(x=4, y=2)
  4. >>> print(result)
  5. 6
  6. >>> print(type(result))
  7. int

Rendering list syntax produces a list:

  1. >>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]')
  2. >>> result = t.render(data=range(5))
  3. >>> print(result)
  4. [1, 2, 3, 4, 5]
  5. >>> print(type(result))
  6. list

Rendering something that doesn’t look like a Python literal produces a string:

  1. >>> t = env.from_string('{{ x }} * {{ y }}')
  2. >>> result = t.render(x=4, y=2)
  3. >>> print(result)
  4. 4 * 2
  5. >>> print(type(result))
  6. str

Rendering a Python object produces that object as long as it is the only node:

  1. >>> class Foo:
  2. ... def __init__(self, value):
  3. ... self.value = value
  4. ...
  5. >>> result = env.from_string('{{ x }}').render(x=Foo(15))
  6. >>> print(type(result).__name__)
  7. Foo
  8. >>> print(result.value)
  9. 15

API¶

class jinja2.nativetypes.NativeEnvironment([options])

An environment that renders templates to native Python types.
class jinja2.nativetypes.NativeTemplate([options])
render(*args, **kwargs)

Render the template to produce a native Python type. If the resultis a single node, its value is returned. Otherwise, the nodes areconcatenated as strings. If the result can be parsed withast.literal_eval(), the parsed value is returned. Otherwise, thestring is returned.

原文:

http://jinja.pocoo.org/docs/2.10/nativetypes/