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'>
2 Answers
Reset to default 0jinja 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)