gpt4 book ai didi

php - 我可以编写一个 Twig 扩展来访问循环中的上一个和下一个元素吗

转载 作者:行者123 更新时间:2023-12-02 21:53:04 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以在 Twig 中创建函数(或其他),这样我就可以访问 for 循环中的下一个和上一个元素。像这样的事情:

{% for i in items %}

{% if i == previous() %}
<p>yes</p>
{% endif %}

{% endfor %}

更新

目标是我有很多检查,例如

if current.name == prev.name 
do somethig
else
do another thing

与下一个相同

在我写了一个排序过滤器之后,问题变得更大了,因为现在

{% set items = allitems|sortbyname %}

{% for item in items %}
{{ item.name }}
{% endfor %}

这里的项目按顺序排列

{% for item in items %}
{{ items[loop.index0].name }}
{% endfor %}

他们不在这里

所以我不能使用类似的东西:

if item.name == items[loop.index0 + 1 ].name 用于访问下一个元素

我不知道如何克服这些问题:(你能帮我吗?

最佳答案

twig 中没有 previous() 这样的东西。
您可以看一下loop variables

您的情况的解决方法是构建自定义迭代器。
这是一个例子

/**
* Previous Next Iterator adds two methods to the ArrayIterator
*
* -> getPreviousElement() To get the previous element of the iterator
* -> getNextElement() To get the next element of the iterator
*
* These methods will not affect the internal pointer
*/
class PreviousNextIterator extends ArrayIterator
{
protected $indexKeys = array();
protected $keyIndexs = array();
protected $elements = array();
protected $dirty = true;

/**
* Constructor
*
* @param array $array Input Array
* @param integer $flags Flags
*/
public function __construct($array = array(), $flags = 0)
{
parent::__construct($array, $flags);

$this->load();
}

/**
* Helper class to self create from an ArrayIterator
*
* @param ArrayIterator $iterator ArrayIterator to fetch
* @return PreviousNextIterator New self instance
*/
public static function createFromIterator(ArrayIterator $iterator)
{
return new self($iterator->getArrayCopy());
}

/**
* Get the previous element of the iterator
*
* @return mixed Previous element
*/
public function getPreviousElement()
{
$index = $this->getIndexKey($this->key());

if (--$index < 0) {
return;
}

$key = $this->getKeyIndex($index);

return $this->elements[$key];
}

/**
* Get the next element of the iterator
*
* @return mixed Next element
*/
public function getNextElement()
{
$index = $this->getIndexKey($this->key());

if (++$index >= $this->count()) {
return;
}

$key = $this->getKeyIndex($index);

return $this->elements[$key];
}

/**
* Loads up the keys
*
* $this->elements
* Contains the copy of the iterator array
* Eg: [ 'a' => $fooInstance1, 'b' => $fooInstance2 ...]
*
* $this->keyIndexs
* Contains the keys indexed numerically
* Eg: [ 0 => 'a', 1 => 'b' ...]
*
* $this->indexKeys
* Contains the indexes of the keys
* Eg: [ 'a' => 0, 'b' => 1 ...]
*/
protected function load()
{
if (!$this->isDirty()) {
return;
}

$this->elements = $this->getArrayCopy();
$this->keyIndexs = array_keys($this->elements);
$this->indexKeys = array_flip($this->keyIndexs);
$this->dirty = false;

}

/**
* Checks whether the loader is dirty
*
* @return boolean
*/
protected function isDirty()
{
return $this->dirty;
}

/**
* Get the Index of a given key
*
* @param string $key Key name
* @return integer Key's index
*/
protected function getIndexKey($key)
{
$this->load();

return array_key_exists($key, $this->indexKeys)
? $this->indexKeys[$key]
: null;
}

/**
* Get the key of a given index
*
* @param integer $index Key's index
* @return string Key name
*/
protected function getKeyIndex($index)
{
$this->load();

return array_key_exists($index, $this->keyIndexs)
? $this->keyIndexs[$index]
: null;
}

/**
* Following methods overrides default methods which alters the iterator
* in order to create a "Dirty state" which will force the reload
*
* You just need to write them all so as to get a complete working class
*/
public function append($value)
{
$this->dirty = true;

return parent::append($value);
}
}

此迭代器添加了两个方法 getPreviousElementgetNextElement

Test Case

class Foo
{
protected $name;

public function __construct($name)
{
$this->name = $name;
}
}


$array = array(
'a' => new Foo('bar'),
'b' => 42,
'c' => new Foo('foobaz'),
'czz' => 'bleh',
);

$iterator = new PreviousNextIterator($array);

foreach ($iterator as $key => $value) {
echo '--- PREVIOUS ---', PHP_EOL;
var_dump($iterator->getPreviousElement());
echo '--- CURRENT ---', PHP_EOL;
var_dump($value);
echo '--- NEXT ---', PHP_EOL;
var_dump($iterator->getNextElement());
echo '----------------', PHP_EOL, PHP_EOL;
}

输出

--- PREVIOUS ---
NULL
--- CURRENT ---
object(Foo)#1 (1) {
["name":protected]=>
string(3) "bar"
}
--- NEXT ---
int(42)
----------------

--- PREVIOUS ---
object(Foo)#1 (1) {
["name":protected]=>
string(3) "bar"
}
--- CURRENT ---
int(42)
--- NEXT ---
object(Foo)#2 (1) {
["name":protected]=>
string(6) "foobaz"
}
----------------

--- PREVIOUS ---
int(42)
--- CURRENT ---
object(Foo)#2 (1) {
["name":protected]=>
string(6) "foobaz"
}
--- NEXT ---
string(4) "bleh"
----------------

--- PREVIOUS ---
object(Foo)#2 (1) {
["name":protected]=>
string(6) "foobaz"
}
--- CURRENT ---
string(4) "bleh"
--- NEXT ---
NULL
----------------

在您返回迭代器的过滤器示例中,只需替换

return $iterator;

return PreviousNextIterator::createFromIterator($iterator);

然后像这样在 TWIG 中使用它

{% for i in items %}

{% if i == items.previousElement %}
<p>Yes</p>
{% endif %}

{% if i == items.nextElement %}
<p>Same Next</p>
{% endif %}

{% endfor %}

关于php - 我可以编写一个 Twig 扩展来访问循环中的上一个和下一个元素吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com