在胡子中的数组内渲染php数组

时间:2014-03-24 17:02:59

标签: php mustache kohana-3.3 kostache

我的数组“$ groupData”如下所示:

 array(3) (
    0 => array(3) (
        "id" => string(1) "2"
        "name" => string(20) "Super Administrators"
        "permissions" => array(3) (
            "system" => integer 1
            "superuser" => string(1) "1"
            "admin" => string(1) "1"
        )
    )
    1 => array(3) (
        "id" => string(1) "3"
        "name" => string(10) "Publishers"
        "permissions" => array(4) (
            "system.pub.add" => integer 1
            "system.pub.delete" => integer 1
            "system.pub.edit" => integer 1
            "system.pub.publish" => integer 1
        )
    )
    2 => array(3) (
        "id" => string(1) "4"
        "name" => string(7) "Authors"
        "permissions" => array(3) (
            "system.pub.add" => integer 1
            "system.pub.delete" => integer 1
            "system.pub.edit" => integer 1
        )
    )
)

我无法呈现代码的permissions部分。我尝试使用{{#groupData}}{{#permissions}} {{.}} {{/permissions}}{{/groupData}},但它不起作用。

1 个答案:

答案 0 :(得分:0)

你的问题是{{ . }} ...你试图将关联数组渲染为字符串,而这在PHP中不起作用:

<?php
echo array('foo' => 1, 'bar' => 2); // no me gusta :)

像大多数Mustache一样,这里的答案是准备你的观点。您期望将该数组渲染为什么? JSON?如果是这样,请明确说明:

<?php
foreach ($data['groupData'] as $key => $group) {
    $data['groupData'][$key]['permissionsJSON'] = json_encode($group['permissions']);
}

$tpl = "{{# groupData }}{{ permissionsJSON }}{{/ groupData }}";

$m = new Mustache_Engine;
echo $m->render($tpl, $data);

如果您希望将其作为键/值对提供,请明确地执行此操作:

<?php
foreach ($data['groupData'] as $key => $group) {
    $permissions = array();
    foreach ($group['permissions'] as $key => $val) {
        $permissions[] = array('key' => $key, 'val' => $val);
    }
    $data['groupData'][$key]['permissions'] = $permissions;
}

$tpl = "{{# groupData }}{{# permissions }}{{ key }}: {{ val }}{{/ permissions }}{{/ groupData }}";

$m = new Mustache_Engine;
echo $m->render($tpl, $data);

您是否只想迭代一个键列表?

<?php
foreach ($data['groupData'] as $key => $group) {
    $data['groupData'][$key]['permissions'] = array_keys($group['permissions']);
}

$tpl = "{{# groupData }}{{# permissions }}{{ . }}{{/ permissions }}{{/ groupData }}";

$m = new Mustache_Engine;
echo $m->render($tpl, $data);