【问题标题】:Sync PHP for loop iterations with twig for loop iterations in OctoberCMS在 OctoberCMS 中将 PHP 循环迭代与 twig 循环迭代同步
【发布时间】:2026-01-11 15:50:01
【问题描述】:

我正在尝试将 PHP 迭代与 twig 迭代同步。

我在 PHP 中有这个 foreach 循环:

foreach ($items as $img) {
      $this['picture'] = $img;
  }

Twig 中的这个 for 循环:

{% for image in gallery %}
   {{picture}} 
{% endfor %}

现在我的输出是一样的,迭代次数是正确的(文件夹里有3张图片,但只有最后一张):

  • img03.jpg
  • img03.jpg
  • img03.jpg

如果我在 PHP 中添加回显:

foreach ($items as $img) {
     echo $this['picture'] = $img;
  }

输出正确,但来自 echo 的内容显示在 HTML 上方。

  • img01.jpg
  • img02.jpg
  • img03.jpg

可以在 Twig 循环中显示正确的输出吗?

【问题讨论】:

  • $this['picture'] 每次都覆盖相同的值。
  • 我是 php 新手,有什么办法可以避免这种覆盖?
  • 我猜你需要调用为 {{ image.picture }}。
  • @CodeBug 已经试过了,循环没有结果。
  • 我终于想通了,将整个数组作为页面变量传递并只用树枝循环它,问题解决了。

标签: php twig octobercms


【解决方案1】:

检查

{% for image in gallery %}
   {{**image**}} 
{% endfor %}

【讨论】: