【问题标题】:Print loop within loop with Twig?使用Twig在循环内打印循环?
【发布时间】:2016-04-29 13:14:45
【问题描述】:

我在 Twig 数组中嵌套了内容。我有几个月,每个月都有几天:

在我的 page.twig 中:

{% set mock = {
  main_title: 'Main title',
  months:
    [
      {
        sub_title: 'Title 1',
        days: [
          {
            monday: 'Lorum',
            tuesday:  'Ipsum'
          }
        ]
      },
      {
        sub_title: 'Title 2',
        days: [
          {
            monday: 'Dolorem',
            tuesday:  'Neque'
          }
        ]
      }
    ]
  }
%}

{% include "component.twig" %}

我正在尝试打印每个月的副标题和它下面的日期文本:

<h2>Title 1</h2>
<h3>Lorum</h3>
<h3>Ipsum</h3>

<h2>Title 2</h2>
<h3>Dolorem</h3>
<h3>Neque</h3>

在component.twig中:

{% for m in months %}
    <h2>{{ m.sub_title }}</h2>

    {% for d in months.days %}
        <h3>Print test</h3>
    {% endfor %}

{% endfor %}

&lt;h2&gt; 中的月份 sub_title 打印正常,但我什至无法让月份中的日期正确循环。

【问题讨论】:

    标签: twig


    【解决方案1】:

    看来错误出在您的第二个循环中。您需要使用 m.days 而不是months.days。

    您的第一个循环将月份拉入变量 m。由于您的主数组月份没有元素天,但每个单独的月份都有,因此您的内部循环当前没有要打印的内容。

    顺便说一句,如果此模板不使用自动转义,我还建议添加转义。

    {% for m in months %}
      <h2>{{m.sub_title| e}}</h2>
      {% for d in m.days %}
         <h3>{{ d| e }}</h3>
       {% endfor %}
    {% endfor %}
    

    -----编辑-----

    我在第一次传递时错过了您的示例数组有一个数组“days”,其中包含一个散列而不是单个级别。在这种情况下,days 键实际上是等效的(在 PHP 中无论如何都是数组中的数组)。

    在这种情况下应该可以解决问题

    {% for m in months %}
      <h2>{{m.sub_title| e}}</h2>
      {% for d in m.days[0] %}
         <h3>{{ d| e }}</h3>
       {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 现在确实打印了 h3,但仅适用于星期一,而不是所有日子。
    • 正如我现在的回答所反映的那样,我错过了您的“天”键是一个包含哈希而不是单个级别的数组。现在应该可以解决问题了。
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 2014-09-05
    • 2015-01-15
    • 2017-04-20
    • 2021-09-24
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多