Jinja2 – 如何获取 Python 的 None 而不是字符串 “None”

huangapple go评论122阅读模式
英文:

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.valueNone,则插入空值。

或者您可以使用:

{
  "value": "{{ example.value if example.value else 'No value!' }}"
}

如果example.valueNone,则插入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.

huangapple
  • 本文由 发表于 2023年5月13日 22:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定