【问题标题】:loop through two objects in the same template遍历同一模板中的两个对象
【发布时间】:2023-01-10 22:59:45
【问题描述】:

我希望能够在模板中并排循环遍历两个对象,如下所示:-

应用.php

return $twig->render('index.twig', ['fixtures' => $fixtures, 'weathers' => $weathers]);

fixtures & weathers 都是包含对象的数组。

模板/index.twig

{% extends "frame.twig" %}
{% block content %}
    {% for fixture in fixtures and weather in weathers %}
        {%  include 'fixture.twig' with [{fixture: fixture}, {weather: weather}] %}
    {% endfor %}
{% endblock %}

应该有 4 行 fixtureweather 数据一起.我得到 8 行 - 4 行带有fixtures,4 行带有weather。那么,循环两次这不是我想要的?

编辑

目标是:

<div class="border py-2 bg-light  mb-3 fixture">
    <div class="row justify-content-md-center text-center teams">
        <div class="col-5 themed-grid-col text-right font-weight-bold text-uppercase">{{ fixture.homeTeam() }}</div>
        <div class="col-2 themed-grid-col">{{ fixture.kickoff() }}</div>
        <div class="col-5 themed-grid-col text-left font-weight-bold text-uppercase">{{ fixture.awayTeam() }}</div>
    </div>
    <div class="text-center font-weight-light location">{{ fixture.location().name() }}</div>
    <div class="text-center font-weight-light location">{{ weather.getTemperature() }}</div>
</div>

我的数据对于对象数组来说很尴尬,我无法做一个简单的 array_merge


array(4) {
  [0]=>
  object(\Fixture)#16 (5) {
    ["id":"\Fixture":private]=>
    int(413456)
    ["awayTeam":"\Fixture":private]=>
    string(15) "Birmingham City"
    ["homeTeam":"\Fixture":private]=>
    string(9) "Brentford"
    ["kickoff":"\Fixture":private]=>
    string(5) "15:00"
    ["location":"\Fixture":private]=>
    object(\Location)#17 (3) {
      ["name":"\Location":private]=>
      string(12) "Griffin Park"
      ["latitude":"\Location":private]=>
      float(51.4872912)
      ["longitude":"\Location":private]=>
      float(-0.3036014)
    }
  }
 
}
array(4) {
  [0]=>
  object(\Weather)#22 (8) {
    ["client":protected]=>
    object(\WeatherApiClient)#23 (6) {
      ["client":protected]=>
      object(GuzzleHttp\Client)#24 (1) {
        ["config":"GuzzleHttp\Client":private]=>
        array(8) {
        
        
        

【问题讨论】:

  • 我建议在后端结合固定装置和天气,这样你就可以迭代一个对象。很难说为什么在不知道对象内容的情况下得到 8 而不是 4。
  • {% for fixture in fixtures and weather in weathers %} - 这甚至应该做什么?
  • 看到我上面的编辑,谢谢

标签: twig


【解决方案1】:

假设根据您的问题,fixturesweathers 是相应的项目,这意味着链接到 fixtureweather 应该/应该具有相同的索引(如果数组是关联的,则为键)。

如果是这种情况,那么您可以将循环更改为以下内容:

{% for key, fixture in fixtures %}
    {%  include 'fixture.twig' with { fixture: fixture, weather: weathers[key]|default } %}
{% endfor %}

demo

【讨论】:

  • 添加了一个编辑以显示我的数据后端的快照
  • 正如我在回答中指出的那样,如果键匹配,那么这个 sn-p 将对你有用。不需要合并任何数组
  • 有用,谢谢
猜你喜欢
  • 2016-11-12
  • 2015-10-15
  • 2015-10-27
  • 2015-01-23
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多