【问题标题】:Iterating over key-value arrays in Twig?在 Twig 中迭代键值数组?
【发布时间】:2017-01-17 00:35:12
【问题描述】:

我(终于)将我的网站从 Drupal7 切换到 Symfony3。

我正在将我的布局迁移到 .twig。

我有一个关于循环和键值数组的问题。

我已经配置了一个 k/v 数组

{% set test = {
        sec1: {
            title:   "title 1",
            content: "content 1"
        },
        sec2: {
            title:   "title 2",
            content: "content 2"
        },
    }
%}

我可以在其他标记中引用任何特定的数组元素。例如,这按预期工作

<ul>
    <li>
        <h1>{{ test.sec1.title }}</h1>
        <div>
            <p>{{ test.sec1.content }}</p>
        </div>
    </li>
</ul>

现在我想在 n 的计数上循环/重复块。但是试试这个,

<ul>
{% for i in 1..5 %}
    <li>
        <h1>{{ test.sec{{ i }}.title }}</h1>
        <div>
            <p>{{ test.sec{{ i }}.content }}</p>
        </div>
    </li>
{% endfor %}
</ul>

引发错误

Unexpected token "punctuation" of value "{" ("end of print statement" expected) in default/index.html.twig at line 67.
500 Internal Server Error - Twig_Error_Syntax

我一直在使用这些变体

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys

但目前还无法进行任何工作。

在键值数组中的 secN 上循环这个列表的正确方法是什么?

【问题讨论】:

    标签: twig symfony symfony-3.1


    【解决方案1】:
           {% for key, item in content.field_invoice_no if key|first != '#' %} 
    <tr>
           <td>{{ item }}</td>
           <td> {{ content.field_invoice_date[key] }}      </td>
    </tr>
            {% endfor %}
    

    在 Twig 中迭代键值数组

    供参考下面的实体代码

     {% for  key, item1 in node.field_quotation.entity.field_product  %} 
         <tr>
            <td>{{ loop.index }}</td>
            <td>{{ item1.entity.body.value |raw }}</td>
             <td> {{ item1.entity.field_product_unit_required.value }}</td>
             <td>{{ item1.entity.field_hsn_code.value }}</td>
            <td>{{item1.entity.field_pro.number|number_format(2, '.', ',')}}</td>
     {% endfor %}        
          </tr>
    

    【讨论】:

      【解决方案2】:

      您的脚本不起作用的原因是您无法像这样编写对象属性访问器。

      你可能需要的是iterating over a subset:

      {% for sec in test|slice(0, 5) %}
          {{ sec.title }}
      {% endfor %}
      

      或者,如果您确实需要访问密钥:iteration over key and value:

      {% for key, sec in test %}
          {{ sec.title }}
          {{key}}
      {% endfor %}
      

      如果您需要在访问密钥的同时进行切片,您可以将后者与loop variables 的检查结合起来:

      {% for key, sec in test %}
          {% if loop.index0 < 5 %}
              {{ sec.title }}
              {{key}}
          {% endif %}
      {% endfor %}
      

      【讨论】:

      • 成功了,谢谢!更有趣的是学习“切片”!有用的...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      相关资源
      最近更新 更多