我在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)
Waq*_*tho 14
如果最多有10个字符串,那么您应该使用列表来迭代所有值.
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
你不能在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)
另一种可能更有意义的方法是将其拆分到控制器中并将拆分列表传递给视图.