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

2

13

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?

Repertoire answered 15/7, 2014 at 12:43 Comment(0)
M
34

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.

Mucronate answered 15/7, 2014 at 12:53 Comment(0)
F
3

If assigned.driver is empty, then the for loop is never executed so the variable won't be defined. What you need to do is to initialize this variable outside of the loop: {% set driverid = null %}

Forest answered 15/7, 2014 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.