mustache - PHP mustache 。隐式迭代器 : How to get key of current value(numeric php array)

标签 mustache mustache.php

如果我有这样的 php 数组:

 $a = array (
    99 => 'Something1',
    184 => 'Something2',
 );

键提供重要信息 - 它可以是一些常量值,ids 等

那么我怎样才能从模板中获取当前元素的 key 。
例如:
{{#data}}

{.} - it is current value, but I need key also.

{{/data}}

在我们的系统中,这类数组太多了,之前重新解析它们会很不舒服。对此有什么更好的解决方案?
非常感谢!

最佳答案

在 Mustache 中迭代关联数组是不可能的,因为 Mustache 将其视为“哈希”而不是可迭代列表。即使您可以遍历列表,您也无法访问 key 。

为此,您必须准备好数据。您可以在将数据传递到 Mustache 之前使用 foreach 循环来完成,或者您可以通过将数组包装在“Presenter”中来完成。像这样的事情应该可以解决问题:

<?php

class IteratorPresenter implements IteratorAggregate
{
    private $values;

    public function __construct($values)
    {
        if (!is_array($values) && !$values instanceof Traversable) {
            throw new InvalidArgumentException('IteratorPresenter requires an array or Traversable object');
        }

        $this->values = $values;
    }

    public function getIterator()
    {
        $values = array();
        foreach ($this->values as $key => $val) {
            $values[$key] = array(
                'key'   => $key,
                'value' => $val,
                'first' => false,
                'last'  => false,
            );
        }

        $keys = array_keys($values);

        if (!empty($keys)) {
            $values[reset($keys)]['first'] = true;
            $values[end($keys)]['last']    = true;
        }

        return new ArrayIterator($values);
    }
}

然后只需将您的数组包装在 Presenter 中:
$view['data'] = new IteratorPresenter($view['data']);

您现在可以在迭代数据时访问键和值:
{{# data }}
    {{ key }}: {{ value }}
{{/ data }}

关于mustache - PHP mustache 。隐式迭代器 : How to get key of current value(numeric php array),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15613903/

相关文章:

php - 如何在mustache.php中使用函数包装器?

php - 带有 JSON 数据的 Mustache.php 抛出可捕获的 fatal error

mustache.php - 在 Mustache 中,有没有办法检查列表是否有项目,但不重复?

java - Mustache.java 传递 json 字符串

javascript - 在 Mustache JS 中包含一个部分

javascript - 向 mustache/php 添加条件

javascript - Mustache.js lambdas 和数字格式化 toFixed

java - java servlet 中的 mustache 模板放置位置以及如何查找

javascript - 如何在 Handlebars 模板中的单选按钮组中设置所选项目?

javascript - mustache .js : why it breaks string into Object of separate characters