0

I have nested content in a Twig array. I have months, each of which have days:

In my 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" %}

I'm trying to print each month's sub title and the day text under it:

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

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

In component.twig:

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

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

{% endfor %}

The month's sub_title in <h2> is printing fine but I can't even get the days in the months to loop correctly.

1 Answer 1

1

It appears that the mistake is in your second loop. Instead of months.days, you need to use m.days.

Your first loop pulls the month into the variable m. As your main array months does not have an element days, but each individual month does, your inner loop currently has no content to print.

Just as a side note, I would also recommend adding escaping if this template doesn't use autoescape.

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

------edit-----

I missed on first pass that your sample array has an array "days" with a hash inside it instead of being a single level. In this case, you actually have the equivalent (in PHP anyway of an array in an array) for the days key.

This should do the trick in this case

{% for m in months %}
  <h2>{{m.sub_title| e}}</h2>
  {% for d in m.days[0] %}
     <h3>{{ d| e }}</h3>
   {% endfor %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

2 Comments

This does print the h3 now but only for monday, not for all of the days.
As my answer now reflects, I missed that your "days" key was an array containing a hash rather than a single level. This should do the trick now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.