Reputation: 79
I have an array in PHP with this structure
$array = array(
'head1' => array(1,2,3),
'head2' => array(4,5,6),
'head3' => array(7,8,9),
);
How can I create an HTML table in twig which have this structure where every array of the $array variable is a column and array keys are table headers?
<table>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>9</td>
</tr>
</table>
Upvotes: 0
Views: 3029
Reputation: 2400
You can do it using the builtin filter keys
. If it's not exactly what you expected, then it is because your array needs to be processed in PHP before passing it to twig
<table>
<thead>
<tr>
{% for key in array|keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in array %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Upvotes: 5