Python 如何在 Jinja2 中将字符串转换为大写/小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23195321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to uppercase / lowercase in Jinja2?
提问by Xar
I am trying to convert to upper case a string in a Jinja template I am working on.
我正在尝试将我正在处理的 Jinja 模板中的字符串转换为大写。
In the template documentation, I read:
在模板文档中,我读到:
upper(s)
Convert a value to uppercase.
So I wrote this code:
所以我写了这段代码:
{% if student.department == "Academy" %}
Academy
{% elif upper(student.department) != "MATHS DEPARTMENT" %}
Maths department
{% endif %}
But I am getting this error:
但我收到此错误:
UndefinedError: 'upper' is undefined
So, how do you convert a string to uppercase in Jinja2?
那么,如何在 Jinja2 中将字符串转换为大写?
采纳答案by Martijn Pieters
Filters are used with the |filter
syntax:
过滤器与以下|filter
语法一起使用:
{% elif student.department|upper != "MATHS DEPARTMENT" %}
Maths department
{% endif %}
or you can use the str.upper()
method:
或者您可以使用以下str.upper()
方法:
{% elif student.department.upper() != "MATHS DEPARTMENT" %}
Maths department
{% endif %}
Jinja syntax is Python-like, not actual Python. :-)
Jinja 语法类似于Python,而不是真正的 Python。:-)
回答by saudi_Dev
And you can use: Filter like this
你可以使用:像这样过滤
{% filter upper %}
UPPERCASE
{% endfilter %}
回答by Jamil Noyda
for the capitalize
为大写
{{ 'helLo WOrlD'|capitalize }}
output
输出
Hello world
for the uppercase
对于大写
{{ 'helLo WOrlD'|upper }}
output
输出
HELLO WORLD