最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - jinja2 Template output int - Stack Overflow

programmeradmin2浏览0评论

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)
发布评论

评论列表(0)

  1. 暂无评论