原生 Python 类型¶
默认Environment
将模板渲染为字符串。 使用NativeEnvironment
,渲染模板将生成原生 Python 类型。
如果使用 Jinja 的上下文不是创建文本文件,这非常有用。 例如,你的代码可能有一个中间步骤,用户可以在其中使用模板来定义值,然后将这些值传递给传统的字符串环境。
示例¶
将两个值相加会得到一个整数,而不是带数字的字符串:
>>> env = NativeEnvironment()
>>> t = env.from_string('{{ x + y }}')
>>> result = t.render(x=4, y=2)
>>> print(result)
6
>>> print(type(result))
int
渲染列表语法生成一个列表:
>>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]')
>>> result = t.render(data=range(5))
>>> print(result)
[1, 2, 3, 4, 5]
>>> print(type(result))
list
渲染看起来不像 Python 字面值的东西会产生一个字符串:
>>> t = env.from_string('{{ x }} * {{ y }}')
>>> result = t.render(x=4, y=2)
>>> print(result)
4 * 2
>>> print(type(result))
str
渲染 Python 对象将生成该对象,不过要求它是唯一的节点:
>>> class Foo:
... def __init__(self, value):
... self.value = value
...
>>> result = env.from_string('{{ x }}').render(x=Foo(15))
>>> print(type(result).__name__)
Foo
>>> print(result.value)
15
API¶
-
class
jinja2.nativetypes.
NativeEnvironment
([options])¶ 将模板渲染为原生 Python 类型的环境。
-
class
jinja2.nativetypes.
NativeTemplate
([options])¶ -
render
(*args, **kwargs)¶ 呈现模板以生成本机 Python 类型。 如果结果是单个节点,则返回其值。 否则,节点将作为字符串连接起来。 如果可以使用
ast.literal_eval()
解析结果,则返回已解析的值。 否则,将返回字符串。
-