web-dev-qa-db-ja.com

文字列をjinjaのリストに分割しますか?

「;」で区切られた文字列である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] }}
54
user3605780

で動作します:

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

最大10個の文字列がある場合、すべての値を反復処理するためにリストを使用する必要があります。

{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
13
Waqar Detho

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) }}

フィルタ関数は次のようになります。

def splitpart (value, index, char = ','):
    return value.split(char)[index]

さらに意味のある別の方法は、コントローラーで分割し、分割したリストをビューに渡すことです。

8
poke