我的控制器中有这样的数组:
foreach ($entities as $temp) {
$semesters[]['romanic'] = $data1;
$semesters[]['grouping'] = data2;
}
如果我的数组像这样$semesters['romanic'][]
,我可以渲染它。但出于某种原因,我无法做到这一点。我试过几次这样的事情:
{% for semester in semesters %}
{{ semester['romanic'] }}
{{ semester['grouping'] }}
{% endfor %}
或
{% for key, semester in semesters %}
{{ semesters[key]['romanic'] }}
{{ semesters[key]['grouping'] }}
{% endfor %}
如果使用2个循环,我可以渲染它:
{% for semester in semesters %}
{% for temp in semester %}
{{ temp }}
{% endfor %}
{% endfor %}
但我只需要1个循环就可以做到这一点。这可能吗?
答案 0 :(得分:1)
你应该改变的第一件事是在PHP中创建你的数组:
foreach ($entities as $temp) {
$c = count($semesters);
$semesters[$c]['romanic'] = $data1;
$semesters[$c]['grouping'] = $data2;
}
在你的Twig中你可以简单地使用:
{% for item in semesters %}
{{ item.romanic }} {{ item.grouping }}<br />
{% endfor %}
以下是测试它的示例PHP代码:
$semesters = array();
$semesters[0]['romanic'] = 1;
$semesters[0]['grouping'] = 2;
$semesters[1]['romanic'] = 3;
$semesters[1]['grouping'] = 4;
$twig->addGlobal ('semesters', $semesters);
echo $twig->render('index.html.twig');
结果是:
1 2
3 4
按预期