Twig模板中如何并行遍历两个对象数组?
解决Twig模板并行遍历两个对象数组的问题
你当前的Twig循环写法{% for fixture in fixtures and weather in weathers %}是错误的,这种写法会被Twig解析为分别遍历两个数组,所以才会输出8行(4行只带fixture数据,4行只带weather数据),而非预期的一一对应4行。
下面提供三种可行的解决方法:
方法1:PHP端提前配对数据
在把数据传给模板之前,用array_map将两个数组按索引配对成关联数组,这样模板里直接遍历新数组即可:
// 在Application.php中修改数据传递逻辑 $pairedItems = array_map(function($fixture, $weather) { return ['fixture' => $fixture, 'weather' => $weather]; }, $fixtures, $weathers); return $twig->render('index.twig', ['pairedItems' => $pairedItems]);
模板中对应的写法:
{% extends "frame.twig" %} {% block content %} {% for item in pairedItems %} {% include 'fixture.twig' with {fixture: item.fixture, weather: item.weather} %} {% endfor %} {% endblock %}
方法2:模板中通过循环索引取对应元素
如果两个数组长度完全一致,可以利用Twig循环自带的loop.index0(从0开始的索引),从另一个数组中取出对应位置的元素:
{% extends "frame.twig" %} {% block content %} {% for fixture in fixtures %} {% set weather = weathers[loop.index0] %} {% include 'fixture.twig' with {fixture: fixture, weather: weather} %} {% endfor %} {% endblock %}
提示:如果两个数组长度不一致,超出的索引会得到
null,可以加{% if weather is not null %}来避免报错。
方法3:用Twig的zip过滤器(需Twig 2.10+)
如果你的Twig版本在2.10及以上,直接用zip过滤器把两个数组打包成两两配对的元组,写法最简洁:
{% extends "frame.twig" %} {% block content %} {% for fixture, weather in fixtures|zip(weathers) %} {% include 'fixture.twig' with {fixture: fixture, weather: weather} %} {% endfor %} {% endblock %}
内容的提问来源于stack exchange,提问作者cookie
相关产品推荐
相关产品推荐

