如果我有这样的 php 数组:
$a = array (
99 => 'Something1',
184 => 'Something2',
);
键表示重要信息 - 它可以是一些常量值、id 等
那么如何从模板中获取当前元素的键。
例如:
{{#data}}
{.} - it is current value, but I need key also.
{{/data}}
在我们的系统中,此类数组太多,并且以前重新解析它们会很不舒服。对此有什么更好的解决方案?
非常感谢!
在 Mustache 中不可能迭代关联数组,因为 Mustache 将其视为“散列”而不是可迭代列表。即使您可以迭代列表,您也无法访问密钥。
为此,您必须准备数据。您可以在将数据传递到 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 }}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)