Reputation: 73
I'm trying to make a dynamic twig template to print lists of Entities with different number of fields. The whole point is that I can't print all the columns of $lligues
.
My controller looks like this:
/**
* @Route("/llistarlliga",name="llistar_lliga")
*/
public function llistarLliga(){
$repository = $this->getDoctrine()->getRepository('AppBundle:Lliga');
$camps = array('Nom','Nº equips','Accions');
$lligues = $repository->findAll();
return $this->render('templates/list.html.twig', array('camps' => $camps, 'lligues' => $lligues,
'title' => 'Llistat de lligues'));
}
Twig template:
{# app/Resources/views/forms/lista.html.twig #}
{% extends "templates/home.html.twig" %}
{% block title %}
{{title}}
{% endblock %}
{% block body %}
<table>
<thead>
{% for i in 0..camps|length-1 %}
<th>{{camps[i]}}</th>
{% endfor %}
</thead>
<tbody>
{% for lliga in lligues %}
<tr>
<td>{{lliga.nom}}</td>
<td>{{lliga.numequips}}</td>
<td>
<a href="{{ path('borrar_lliga', {'nom' : lliga.nom}) }}"><img src="{{ asset('images/bin.png') }}" /></a>
<a href="{{ path('modificar_lliga', {'nom' : lliga.nom}) }}"><img src="{{ asset('images/edit.png') }}" /></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
So, I would like to change the second loop (for lliga in lligues) to make it dynamic, so if it has more fields or less, it prints them too.
Thanks to everyone!
Upvotes: 1
Views: 2466
Reputation: 196
You can create a twig filter cast_to_array
.
First you need to create the custom filter. Something like this:
namespace AppBundle\Twig;
class ArrayExtension extends \Twig_Extension
{
/**
* @inheritDoc
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('cast_to_array', array($this, 'castToArray'))
);
}
public function castToArray($stdClassObject) {
$response = array();
foreach ($stdClassObject as $key => $value) {
$response[] = array($key, $value);
}
return $response;
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'array_extension';
}
}
And add it to your app\config\services.yml
:
services:
app.twig_extension:
class: AppBundle\Twig\ArrayExtension
public: false
tags:
- { name: twig.extension }
Finally, you case use your custom filter in your Twig templates:
{# app/Resources/views/forms/lista.html.twig #}
{% extends "templates/home.html.twig" %}
{% block title %}
{{title}}
{% endblock %}
{% block body %}
<table>
<thead>
{% for i in 0..camps|length-1 %}
<th>{{camps[i]}}</th>
{% endfor %}
</thead>
<tbody>
{% for lliga in lligues %}
<tr>
{% for key, value in lliga|cast_to_array %}
<td>{{ value }}</td>
{% endfor %}
<td>
<a href="{{ path('borrar_lliga', {'nom' : lliga.nom }) }}"><img src="{{ asset('images/bin.png') }}" /></a>
<a href="{{ path('modificar_lliga', {'nom' : lliga.nom }) }}"><img src="{{ asset('images/edit.png') }}" /></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
I believe this could do the trick.
Upvotes: 3