【问题标题】:Looping through multidimentional array in twig循环遍历树枝中的多维数组
【发布时间】:2014-03-31 14:39:56
【问题描述】:

我在一个 php 模型中创建了这个多重数组。在下面。

$handle = opendir($this->path);

while(false !== ($file = readdir($handle)))
{
    if($file != "." && $file != "..")
    {
        $this->content[] = array(
            'name' => $file,
            'name_href' => $file,
            'extn' => $this->findExts($file),
            'file_size' => number_format(filesize($this->path . '/' . $file)),
            'mod_time' => date("M j Y g:i A", filemtime($this->path . '/' . $file)),
            'time_keys' => date("YmdHis", filemtime($this->path . '/' . $file))
        );
    }
}
closedir($handle);

我正在尝试用树枝遍历它。但是页面没有显示任何内容。但是,如果我 print_r $content 数组显示所有数据,所以我知道数组不为空。有人可以帮我找出如何循环并显示内容。

这是我尝试过的

{% for key, value in content %}
    <li>
       <a class="show_content" href="{{ value.name_href }}">{{ value.name }}</a>
    </li>
{% endfor %}

但这不会显示任何内容。这是我将内容传递到树枝模板的地方。

$template = $twig->loadTemplate('layout.html.twig');
$template->display(array('content' => $content));

【问题讨论】:

  • 为什么会这样? $this->content[] ,为什么不 $this->content
  • @mpm 因为它在一个while循环中,所以它会迭代多次
  • dump(value) 看看它的样子
  • 在哪里渲染模板?

标签: php twig


【解决方案1】:

所以问题不在于循环。它工作正常。

问题是我没有以正确的方式传递内容,我只是没有注意。愚蠢的错误。

我有这个: $template-&gt;display($content);

它必须是这个 $template-&gt;display(array('content' =&gt; $content));

【讨论】:

  • 你应该看看 php glob 函数来避免这种老式的遍历文件的方式。
猜你喜欢
  • 1970-01-01
  • 2016-09-02
  • 2013-04-01
  • 2012-04-21
相关资源
最近更新 更多