我在 jinja2 模板中有一些变量,它们是用“;”分隔的字符串。
我需要在代码中单独使用这些字符串。 即变量是variable1 =“green;blue”
{% list1 = {{ variable1 }}.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
我可以在渲染模板之前将它们分开,但由于有时字符串内最多有 10 个字符串,这会变得混乱。
我之前做的地方有一个jsp:
<% String[] list1 = val.get("variable1").split(";");%>
The grass is <%= list1[0] %> and the boat is <%= list1[1] %>
编辑:
它适用于:
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
5年后回到我自己的问题并看到这么多人发现这个有用,一个小小的更新。
可以使用 split 函数将字符串变量拆分为
list
(它可以包含相似的值,set
用于赋值)。我在官方文档中没有找到这个函数,但它的工作原理与普通Python类似。这些项目可以通过索引调用,在循环中使用,或者像戴夫建议的那样,如果你知道这些值,它可以设置像元组这样的变量。
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
或
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
或
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
如果最多有 10 个字符串,那么您应该使用列表来迭代所有值。
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
你不能在 jinja 中运行任意 Python 代码;在这方面它的工作方式与 JSP 不同(只是看起来很相似)。 jinja 中的所有内容都是自定义语法。
出于您的目的,定义一个 自定义过滤器 是最有意义的,因此您可以执行以下操作:
The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{ splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{ splitpart(1) }}
过滤器函数可能如下所示:
def splitpart (value, index, char = ','):
return value.split(char)[index]
另一种可能更有意义的方法是在控制器中拆分它并将拆分的列表传递给视图。
定义自定义过滤器非常容易。在 Flask 的 Jinja 版本中,它看起来像这样:
@app.template_filter("split")
def split(value: str, separator=" ", maxsplit: int = -1):
return value.split(separator, maxsplit)
并且无需Flask,也可以类似地完成:
def split(value: str, separator=" ", maxsplit: int = -1):
return value.split(separator, maxsplit)
environment.filters["split"] = split
用途:
{{ commit.message | split }}