loopssymfonytwig

Access to the next value in a Twig loop


I have a problem to display the next line of a result in a loop using Twig :

// Arkiglass/ProduitBundle/Controller/DefaultController.php
<?php
public function produitAction()
{
$em = $this->getDoctrine()->getManager();
        $query = $em->createQuery('SELECT p FROM ArkiglassProduitBundle:Produit p');
        $produit = $query->getResult();
        if (!$produit)
        {
            throw $this->createNotFoundException('no such Product !');
        }
return $this->render('ArkiglassSiteBundle:Site:produit.html.twig', array(
            'produit' => $produit
        ));;
}

here is my Template

{# produit.html.twig #}

{% for pr in produit %}
<table>
    <tr>
        <td>
            {{ pr.description }}
        </td>
        <td>
            {# display the next pr.description #}
        </td>

    </tr>
 {% endfor %}
 </table>

I tried to use {{ pr[loop.index+1].description }} but it didn't work for me.


Solution

  • This is one possible solution to print two loop-runs in a row. The loop indexes (first the 1 based, then the 0 based) are modulo by 2, so in the first run, the leading <tr> gets rendered, in the second run the trailing </tr> gets rendered. And so on.
    The first loop.last condition is to show a second empty column, if the last loop-run ends in the first column. The second condition is to close the row correctly.

    <table>
        {% for pr in produit %}
            {% if (loop.index % 2) %}<tr>{% endif %}
                <td>
                    {{ pr.description }}
                </td>
                {% if (loop.index % 2) and loop.last %}
                    <td>&nbsp</td>
                {% endif %}
            {% if (loop.index0 % 2) or loop.last %}</tr>{% endif %}
        {% endfor %}
     </table>