1

My controller sends to Twig the following associative array in a variable called 'petition';

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [doctype] => "somedoc"
            [nrdoc] => "99"
            [datadoc] => "2015-01-01"
        )
    [1] => stdClass Object
        (
            [id] => 2
            [doctype] => "otherdoc"
            [nrdoc] => "100"
            [datadoc] => "2015-01-01"
        )
)

Then, in my Twig template (view) I'm doing this:

    {% for id in petition %}

        {% if id.doctype == 'somedoc' %}
            {{id.nrdoc}} / {{id.datadoc}}
        {% else %}
                UNDEFINED!
        {% endif %}

    {% endfor %}

The problem is that I can't figure out the logic of how to output "UNDEFINED!" only once, if the doctype != "somedoc" when there are other key->value elements in the array. The way I'm doing it, it will output "UNDEFINED!" everytime the script loops...

Thank you in advance for your help

Gabriel

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49

1 Answers1

2

One variant is to define an extra variable for this:

{% set undefined = false %}

{% for id in petition %}
    {% if id.doctype == 'somedoc' %}
        {{ id.nrdoc }} / {{ id.datadoc }}
    {% else %}
        {% set undefined = false %}
    {% endif %}
{% endfor %}

{% if undefined == true %}
    UNDEFINED!
{% endif %}

You can read more about setting Twig variables here.

chapay
  • 1,315
  • 1
  • 13
  • 20
  • Thank you, chapay ! if I was doing it in php I would have done it on similar logic. Unfortunately I'm new to Twig and I was not aware of the fact that it can actually define variables within the template! you saved my day :)... yes, I know... should have read about it in docs... :) – Gabriel Maftei Nov 12 '15 at 12:42
  • @GabrielMaftei You are welcome! Please accept the answer if you consider it's helpful. – chapay Nov 12 '15 at 13:07