在神社中将字符串拆分为列表?

Split string into list in jinja?

我在 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] }}

你不能在 jinja 中 运行 任意 Python 代码;在这方面它不像 JSP 那样工作(它看起来很相似)。 jinja 中的所有内容都是自定义语法。

为了您的目的,定义一个 custom filter 最有意义,因此您可以执行以下操作:

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]

另一种可能更有意义的方法是在控制器中拆分它并将拆分后的列表传递给视图。

5 年后回到我自己的问题,看到这么多人觉得这很有用,稍微更新一下。

一个字符串变量可以使用拆分函数拆分成一个list(它可以包含类似的值,set 是针对assignment)。我没有在官方文档中找到这个函数,但它的工作原理与正常 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 %}