0

Hi I am looking for a way to check to see if a field has content within an array of fields. If any of the fields have content I want text to display, but only once so I can't just use a for loop.

The below solution works but there must be a better way to do this?

{% set foo = 0 %}
{% for field_group in item if field_group.sticky_nav|length %}
    {% set foo = 1 %}
{% endfor %}

{% if foo >= 1 %}
    <p>Text</p>
{% endif %}

Item looks something like this

[item] => Array
    (
        [0] => Array
            (
                [title] =>
                [description] =>
                [link] =>
                [sticky_nav] => foo
            )
        [1] => Array
            (
                [title] =>
                [description] =>
                [image] =>
                [sticky_nav] => bar
            )
    )

I'm really looking for a solution like the following which doesn't work.

{% if field_group.sticky_nav in item %}
    <p>Text</p>
{% endif %}

Does anyone know of a solution for this?

0

Simple answer: no. According to what Twig is capable of doing, your loop is optimized as is.

The better way of doing it is to check the values with a php loop and then sending the flag to Twig.

  • Thanks for the answer. If that's the case I'll just leave it as is. It's a once off snippet so I'm not going to worry about it further. – JeffTalbot Jan 30 '17 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.