如何在 Jinja2中将字符串转换为大写/小写?

我正在尝试将金贾模板中的字符串转换为大写。

模板文档中,我读到:

upper(s)
Convert a value to uppercase.

所以我写了这段代码:

{% if student.department == "Academy" %}
Academy
{% elif  upper(student.department) != "MATHS DEPARTMENT" %}
Maths department
{% endif %}

但我得到了这个错误:

UndefinedError: 'upper' is undefined

那么,如何在 Jinja2中将字符串转换为大写呢?

120202 次浏览

Filters are used with the |filter syntax:

{% elif  student.department|upper != "MATHS DEPARTMENT" %}
Maths department
{% endif %}

or you can use the str.upper() method:

{% elif  student.department.upper() != "MATHS DEPARTMENT" %}
Maths department
{% endif %}

Jinja syntax is Python-like, not actual Python.

And you can use: Filter like this

{% filter upper %}
UPPERCASE
{% endfilter %}

for the capitalize

\{\{ 'helLo WOrlD'|capitalize }}

output

Hello world

for the uppercase

\{\{ 'helLo WOrlD'|upper }}

output

HELLO WORLD

For Capitalize

\{\{ 'helLo WOrlD'|capfirst }}

For UPPER CASE

\{\{ 'helLo WOrlD'|upper }}

For lower case

\{\{ 'helLo WOrlD'|lower }}

For title

\{\{ 'helLo WOrlD'|title }}

For ljust

\{\{ 'helLo WOrlD'|ljust }}

For rjust

\{\{ 'helLo WOrlD'|rjust }}

For wrap

\{\{ 'helLo WOrlD'|wrap }}

Hope It Helps