Twig: set a variable inside a loop, use it outside that loop

ReynierPM picture ReynierPM · Jul 15, 2014 · Viewed 18.8k times · Source

I'm trying to define driverid, using set, as a var in for driver in assigned.driver cycle for use later. See below what I'm doing:

{% for key, assigned in pgn %}
    <tr id="device-{{ assigned.id }}">
        <td>{{ assigned.imei }}</td>
        <td>{{ assigned.description }}</td>
        <td>
            {% for driver in assigned.driver %}
                {{ driver.driver.id }} {# check if driver.driver.id has values testing purposes - delete me #}
                {% set driverid = driver.driver.id %}

                {% if driver.driver.name != "" %}
                    {% if driver.driver.name %}
                        {{ driver.driver.name }}
                    {% else %}
                        -
                    {% endif %}
                {% endif %}
            {% endfor %}
        </td>
        <td>
            <button class="btn btn-xs btn-default"
                    onclick="openAlert({{ assigned.id }}, {{ driverid }}, 'unlink')"
                    data-original-title="{{ "devices.actions.unlink"|trans }}"
                    title="{{ "devices.actions.unlink"|trans }}">
                <i class="fa fa-times"></i>
            </button>
            <button class="btn btn-xs btn-default"
                    onclick="openAlert({{ assigned.id }}, null, 'delete')"
                    data-original-title="{{ "button.delete"|trans }}"
                    title="{{ "button.delete"|trans }}">
                <i class="fa fa-times"></i>
            </button>
        </td>
    </tr>
{% endfor %}

But I get this error:

Variable "driverid" does not exist in /var/www/html/src/Device/DeviceBundle/Resources/views/List/listDevices.html.twig at line 74

What's the right way to set that var to use later on openAlert() call? Or in others words how I get the driver.driver.id to pass it as a parameter to openAlert() function?

Answer

Paolo Stefan picture Paolo Stefan · Jul 15, 2014

As they say here, this is not a bug, it's a feature: variables defined inside a loop are scoped to that loop.

But don't worry, you can define the var outside the loop and assign it inside, like this:

{% set driverid = '' %} {# <-- add this line: default empty value #}

{% for driver in assigned.driver %}
     ...
     {% set driverid = driver.driver.id %}

this should be enough to make it work.