So I wanted to create a twig template that would render a table, just by defining the table headers, and pass an array of entities. The problem was that I also wanted to add action buttons like edit and delete, but the URL should be created dynamically with a changing ID. This is what I came up with.
So along with the array of entities that are passed to the twig template, an array with table Headers is being added too. The array with headers contains the id inside the entity, the name of the header, and the third element is the ‘type’. This way I can render the field as a date/time object. I also use this to set the type to action, which means I have an array with action buttons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$arr['tableColumns'] = array( array('id', 'Id'), array('jaar', 'Jaar'), array('naam', 'Naam'), array('weekNummerIntern', 'Week nr int'), array('weekNummerExtern', 'Week nr ext'), array('datumBegin', 'Datum Begin', 'date'), array('bedragDeelnamePrijs', 'Bedrag'), array('weekSoort', 'Week soort'), array('actions', 'Actions', 'actions', array( array( 'pathName' => 'week_show', 'pathVars' => array('id' => 'id'), 'anchor' => '<i class="fa fa-eye"></i>', ), array( 'pathName' => 'week_edit', 'pathVars' => array('id' => 'id'), 'anchor' => '<i class="fa fa-pencil"></i>', ) )), ); |
Then in Twig, I render the table like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
{% if entities is defined and entities is iterable and entities|length > 0 %} <table id="weekTable" class="table table-striped table-bordered" width="100%" cellspacing="0"> <thead> <tr> {% for columnData in tableColumns %} <th>{{ columnData[1] }}</th> {% endfor %} </tr> </thead> <tbody> {% for entity in entities %} <tr> {% for columnData in tableColumns %} <td> {% if columnData[2] is defined %} {% if columnData[2] == 'date' %}{{ attribute(entity, columnData[0])|date('Y-m-d H:i:s') }}{% endif %} {% if columnData[2] == 'actions' %} {% for buttonData in columnData[3] %} {% set arr = [] %} {% for key,value in buttonData.pathVars %} {% set arr = arr|merge({ (key) : (attribute(entity, value)) }) %} {% endfor %} <a href="{{ path(buttonData.pathName, arr ) }}" class="btn btn-default">{{ buttonData.anchor|raw }}</a> {% endfor %} {% endif %} {% else %} {{ attribute(entity, columnData[0]) }} {% endif %} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endif %} |
The array with options that is being passed to Twig’s path tag, is being build up in Twig itself.