如何在 Mustache 中迭代对象数组

How to Iterate an array of objects in Mustache

我有一组对象被设置为 Mustache 渲染函数:

 require 'vendor/Mustache/Autoloader.php';
    Mustache_Autoloader::register();
    $m = new Mustache_Engine();

echo $m->render($template, $data);

$data 包含对象数组,如下所示:

(这是 http://www.jsoneditoronline.org 的屏幕截图,我已打开其中一个对象供您参考)

现在在我的 $template 代码中我有这个:

         {{#.}} 
                <article>

                    <h1>
                        <a href="layouts_post.html">{{name}}</a>
                    </h1>

                    <p>{{{text}}}</p>

                    <h2>{{jobtitle}}</h2>

                </article>
         {{/.}}

迭代不起作用,我想知道是否有一种方法可以让 Mustache 像上面那样迭代对象数组。

(仅供参考 - 我已尝试重建我的数据,但没有成功。每次 Mustache 都无法迭代。)

非常感谢您的提前帮助。

好的,我解决了...

为了让 Mustache 有一个包含变量,它需要在渲染函数中作为参数赋值。所以为了让它工作,我将 $data 数组分配给 'data' 键:

require 'vendor/Mustache/Autoloader.php';
Mustache_Autoloader::register();
$m = new Mustache_Engine();

echo $m->render($template, array('data' => $data));

现在 'data' 成为小胡子模板中的主要变量:

       {{#data}} 
                <article>

                    <h1>
                        <a href="layouts_post.html">{{name}}</a>
                    </h1> 

                    <p>{{{text}}}</p>

                    <h2>{{jobtitle}}</h2>

                </article>
       {{/data}}

事实上,您可以在此函数中分配大量数组,并在模板布局中使用它们:

require 'vendor/Mustache/Autoloader.php';
Mustache_Autoloader::register();
$m = new Mustache_Engine();

echo $m->render($template, array('data' => $data, 'anotherValue' => $someOtherData));

似乎很明显我知道...