回答问题

我在 jinja2 模板中有一些变量,它们是由“;”分隔的字符串。

我需要在代码中单独使用这些字符串。即变量是 variable1 u003d "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] }}

Answers

在 5 年后回到我自己的问题并看到这么多人发现这很有用,有点更新。

可以使用 split 函数将字符串变量拆分为list(它可以包含相似的值,set用于赋值)。我在官方文档中没有找到这个函数,但它的工作原理类似于普通的 Python。这些项目可以通过索引调用,在循环中使用,或者像 Dave 建议的那样,如果你知道这些值,它可以像元组一样设置变量。

{% 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 }}
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐