英文:
Jinja2 - How to get python None instead of string "None"
问题
在Jinja2中,如何使用Python的None而不是字符串"None"?
{
"value": "{{ example.value if example.value is defined else none }}"
}
example.value
可能不存在。
英文:
In Jinja2 how to python None instead of string "None"?
{
"value": "{{ example.value }}"
}
example.value
may absent.
答案1
得分: 1
如果这是在脚本标签内部,您可以在脚本开头声明一个常量:
const None = null;
这将替换您传递到模板的所有Python的None
值为JavaScript的等效null
。
如果这是在HTML中渲染的,您可以使用以下方式:
{
"value": "{{ example.value if example.value }}"
}
如果example.value
是None
,则插入空值。
或者您可以使用:
{
"value": "{{ example.value if example.value else 'No value!' }}"
}
如果example.value
是None
,则插入No value!
。
英文:
If this is inside of a script tag, you can declare a constant at the beginning of the script:
const None = null;
This will replace all of Python's None
values that you pass to the template with JavaScript's equivalent null
.
If this is rendering in the HTML itself, you can use:
{
"value": "{{ example.value if example.value }}"
}
This inserts a blank value if example.value
is None
.
Or you can use:
{
"value": "{{ example.value if example.value else 'No value!' }}"
}
Which inserts No value!
if example.value
is None
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论