title: Twig: set a variable inside a loop, use it outside that loop
body: <p>I'm trying to define <code>driverid</code>, using <code>set</code>, as a var in <code>for driver in assigned.driver</code> cycle for use later. See below what I'm doing:</p>
  
  <pre><code>{% for key, assigned in pgn %}
      &lt;tr id="device-{{ assigned.id }}"&gt;
          &lt;td&gt;{{ assigned.imei }}&lt;/td&gt;
          &lt;td&gt;{{ assigned.description }}&lt;/td&gt;
          &lt;td&gt;
              {% 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 %}
          &lt;/td&gt;
          &lt;td&gt;
              &lt;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 }}"&gt;
                  &lt;i class="fa fa-times"&gt;&lt;/i&gt;
              &lt;/button&gt;
              &lt;button class="btn btn-xs btn-default"
                      onclick="openAlert({{ assigned.id }}, null, 'delete')"
                      data-original-title="{{ "button.delete"|trans }}"
                      title="{{ "button.delete"|trans }}"&gt;
                  &lt;i class="fa fa-times"&gt;&lt;/i&gt;
              &lt;/button&gt;
          &lt;/td&gt;
      &lt;/tr&gt;
  {% endfor %}
  </code></pre>
  
  <p>But I get this error:</p>
  
  <blockquote>
    <p>Variable "driverid" does not exist in
    /var/www/html/src/Device/DeviceBundle/Resources/views/List/listDevices.html.twig
    at line 74</p>
  </blockquote>
  
  <p>What's the right way to set that var to use later on <code>openAlert()</code> call? Or in others words how I get the <code>driver.driver.id</code> to pass it as a parameter to <code>openAlert()</code> function?</p>