6

私は小枝を使用し、配列にいくつかのデータを持っています。for ループを使用して、次のようにすべてのデータにアクセスします。

{% for item in data %}
    Value : {{ item }}
{% endfor %}

ループで前のアイテムにアクセスすることは可能ですか? 例: n 個のアイテムを使用している場合、 n-1 個のアイテムにアクセスしたいとします。

4

3 に答える 3

9

これを行う組み込みの方法はありませんが、回避策は次のとおりです。

{% set previous = false %}
{% for item in data %}
    Value : {{ item }}

    {% if previous %}
        {# use it #}
    {% endif %}

    {% set previous = item %}
{% endfor %}

最初の反復には if が必要です。

于 2013-04-06T09:05:23.207 に答える
0

私の解決策:

{% for item in items %}

  <p>item itself: {{ item }}</p>

  {% if loop.length > 1 %}
    {% if loop.first == false %}
      {% set previous_item = items[loop.index0 - 1] %}
      <p>previous item: {{ previous_item }}</p>
    {% endif %}

    {% if loop.last == false %}
      {% set next_item = items[loop.index0 + 1] %}
      <p>next item: {{ next_item }}</p>
    {% endif %}

  {% else %}

    <p>There is only one item.</p>

  {% endif %}
{% endfor %}

最初のアイテムの前が最後に、最後のアイテムの後に最初のアイテムが続く無限の画像ギャラリーを作成する必要がありました。次の方法で実行できます。

{% for item in items %}

  <p>item itself: {{ item }}</p>

  {% if loop.length > 1 %}
    {% if loop.first %}
      {% set previous_item = items[loop.length - 1] %}
    {% else %}
      {% set previous_item = items[loop.index0 - 1] %}
    {% endif %}

    {% if loop.last %}
      {% set next_item = items[0] %}
    {% else %}
      {% set next_item = items[loop.index0 + 1] %}
    {% endif %}

    <p>previous item: {{ previous_item }}</p>
    <p>next item: {{ next_item }}</p>

  {% else %}

    <p>There is only one item.</p>

  {% endif %}
{% endfor %}
于 2014-11-16T08:11:15.867 に答える