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

use*_*780 55 python jinja2

我在jinja2模板中有一些变量,这些变量是由';'分隔的字符串.

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

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

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

在我做之前我有一个jsp:

<% String[] list1 = val.get("variable1").split(";");%>    
The grass is <%= list1[0] %> and the boat is <%= list1[1] %>
Run Code Online (Sandbox Code Playgroud)

编辑:

它适用于:

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
Run Code Online (Sandbox Code Playgroud)

use*_*780 93

它适用于:

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
Run Code Online (Sandbox Code Playgroud)

  • Jinja2还将分配扩展元组样式ala` {%set list1,list2 = variable1.split(';')%}`. (8认同)
  • @emi 它之所以有效,是因为 https://jinja.palletsprojects.com/en/3.0.x/templates/#python-methods :`Python 方法您还可以使用在变量类型上定义的任何方法。方法调用返回的值用作表达式的值。下面是一个使用在字符串上定义的方法的示例(其中 page.title 是一个字符串): {{ page.title.capitalize() }}` (3认同)
  • `split` 函数是字符串对象中存在的函数(所有字符串方法都可以从 jinja2 模板中获取?):https://www.geeksforgeeks.org/python-string-split/ (2认同)

Waq*_*tho 14

如果最多有10个字符串,那么您应该使用列表来迭代所有值.

{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


pok*_*oke 8

你不能在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) }}
Run Code Online (Sandbox Code Playgroud)

过滤器功能可能如下所示:

def splitpart (value, index, char = ','):
    return value.split(char)[index]
Run Code Online (Sandbox Code Playgroud)

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

  • 我在哪里放置过滤功能? (2认同)
  • 我做到了-这就是为什么我问。我在Ansible的上下文中使用它,因此找到了一个更相关的答案。还是谢谢https://groups.google.com/forum/#!topic/ansible-project/A7fGX-7X-ks。:) (2认同)