gpt4 book ai didi

python - 将字符串拆分为jinja中的列表?

转载 作者:IT老高 更新时间:2023-10-28 20:25:25 29 4
gpt4 key购买 nike

我在 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 用于 assignment )。我在官方文档中没有找到这个函数,但它的工作原理类似于普通的 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 }}

关于python - 将字符串拆分为jinja中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515456/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com