N
N
Nikita Gusakov2013-04-15 11:43:40
PHP
Nikita Gusakov, 2013-04-15 11:43:40

Can't figure out how to validate an array in twig?

Here is a macro slightly modified from a similar stackoverflow question

{% macro menu(links) %}
    {% for key, link in links %}
        <li>
            <a href="{{ link }}">{{ key }}</a>
            {% if link.sublink %}
                <ul>
                    {{ _self.menu_links(link[key]) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

But link has no sublink and no hassublinks filter. How to write yourself? Or are there still methods of checking inside the twig core?
if link is array - also does not work, there is no such check.
An array is supplied as input, if necessary I can give var_dump, in yml it looks like this:
Главная: /
Контакты: /contacts
Форум: /forum
О нас: /about
Услуги:
    Услуга1: /one
    Услуга2: /two

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
JekaRu, 2013-04-15
@hell0w0rd

Here's what I came up with, it should work as expected:

{% if  (link|keys)|length>0 %}

S
stnw, 2013-04-15
@stnw

maybe link.length?

J
JekaRu, 2013-04-15
@JekaRu

Maybe so?

{% if link.sublink is defined and link.sublink|length>0 %}

K
Koroalen, 2020-04-19
@Koroalen

So:
{% if link is iterable %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question