1

A small Twig question regarding array in array access. I have the following script, which is essentially listing categories, and then the subcategories associated to each category.

{% for category in categories %}

    <li>
        <a href="#">{{ category.name }}</a>

        {% if category.subcategories|length > 0 %}

        {% set subcategories  = category.subcategories %}

        <ul>
            {% for subcategory in subcategories %}

            <li>
                <a href="#">{{ subcategory.name }}</a>
            </li>

            {% endfor %}
        </ul>
        {% endif %}
    </li>

{% endfor %}

The script above does not display subcategories and I have no clue as to why. The main problem is the fact that the for loop is never accessed. Dumping the subcategories variable right after setting it reveals the expected, that it holds the correct array, with one element.

Any ideas?

Dumping the subcategories variable reveals:

array (size=2)
  0 => 
    array (size=2)
      'id' => int 1
      'name' => string 'Dolls' (length=5)
  1 => 
    array (size=2)
      'id' => int 2
      'name' => string 'Test' (length=4)
4
  • This code is good. If your category has one or more subcategories, this code should print them. Revise you really have subcategories. Commented Sep 8, 2013 at 23:01
  • Hey, provided a dump() of the subcategories variable. Still not luck. Commented Sep 8, 2013 at 23:03
  • 2
    Why don't you use directly {% for subcategory in category.subcategories %}? Commented Sep 8, 2013 at 23:05
  • Tried that initially, but thought that I was maybe asking too much of Twig to some extent. Anyway, found answer, thanks for the optimisation. Commented Sep 8, 2013 at 23:12

1 Answer 1

1

Problem was actually not related to Twig at all in this case, but to a class that was applied to the li item that held everything together, that only displayed the content when a specific class was applied to it.

In a very bizarre way, the node simply got deleted by a JS when the class was not applied, so firebug would not pick it up. Eventually stumbled into it on the page source, and that's how I got to the solution.

Sign up to request clarification or add additional context in comments.

Comments

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.