Reputation: 337
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.
Upvotes: 3
Views: 10432
Reputation: 1048
This could seem a bit unelegant, but will avoid you the two loops.
<tbody>
{% set previousOption = false %}
{% set nextIterator = 1 %}
{% for option in options %}
{% if options[nextIterator] is defined %}
{% set nextOption = options[nextIterator] %}
{% else %}
{% set nextOption = false %}
{% endif %}
<tr>
<td>
{{ option.label }}
</td>
<td>
{{ option.type }}
</td>
<td colspan>
<a href="{{ path('option_delete', {'questionId': question.id, 'optionId': option.id }) }}">Delete option</a>
</td>
<td>
{% if previousOption %}
<a href="{{ path('do_swap', {'optionId': option.id, 'optionId2': previousOption.id }) }}">« Boost up</a>
{% endif %}
</td>
<td>
{% if nextOption %}
<a href="{{ path('do_swap', {'optionId': option.id, 'optionId2': nextOption.id }) }}">Shut down »</a>
{% endif %}
</td>
</tr>
{% set previousOption = option %}
{% set nextIterator = (nextIterator + 1) %}
{% endfor %}
</tbody>
Upvotes: 1
Reputation: 10085
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> </td>
{% endif %}
{% if (loop.index0 % 2) or loop.last %}</tr>{% endif %}
{% endfor %}
</table>
Upvotes: 10