admin管理员组

文章数量:1389783

jinja2 Template cannot get primitive types?

Here's my test:

x = jinja2.Template('{{x|int}}',).render(x=1)
type(x)
<class 'str'>

Hopefully the result will be:<class 'int'>

jinja2 Template cannot get primitive types?

Here's my test:

x = jinja2.Template('{{x|int}}',).render(x=1)
type(x)
<class 'str'>

Hopefully the result will be:<class 'int'>

Share Improve this question asked Mar 14 at 3:20 984958198984958198 336 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

jinja is by design made for rendering text based templates (eg. html). even as you specify {{x|int}} it will still change into a string when .render() is called

method 1:
converting to int outside of the Template

x = int(jinja2.Template('{{x|int}}',).render(x=1))

method 2:
using Native Environment to return primitive types (Jinja2 3.0+)

from jinja2.nativetypes import NativeEnvironment
template = NativeEnvironment().from_string("{{x|int}}")
x = template.render(x=1)
print(type(x))

Template.render always returns a string and this is by design. https://jinja.palletsprojects/en/stable/api/#jinja2.Template.render

If you need to convert you would have to

x = jinja2.Template('{{x|int}}',).render(x=1)
x_int = int(x)

本文标签: pythonjinja2 Template output intStack Overflow