在Jinja中将字符串拆分为列表? [英] Split string into list in jinja?

查看:221
本文介绍了在Jinja中将字符串拆分为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jinja2模板中有一些变量,这些变量用';'分隔.

I have some variables in a jinja2 template which are strings seperated by a ';'.

我需要在代码中单独使用这些字符串. 即变量为variable1 ="green; blue"

I need to use these strings separately in the code. i.e. the variable is variable1 = "green;blue"

{% list1 = {{ variable1 }}.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

我可以在呈现模板之前将它们拆分开,但是由于有时在字符串中最多包含10个字符串,因此会变得混乱.

I can split them up before rendering the template but since it are sometimes up to 10 strings inside the string this gets messy.

在做之前,我有一个jsp:

I had a jsp before where I did:

<% 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年后回到我自己的问题后,看到很多人发现此功能有用,做了一些更新.

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

可以使用拆分功能将字符串变量拆分为list(它可以包含相似的值,set用于

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

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

这篇关于在Jinja中将字符串拆分为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆