我正在使用@each blade指令循环查询结果数组并渲染它们(在这种情况下,@each指令往往比foreach循环更好一点,因为HTML将会是根据查询结果呈现更改)。这一切都运行正常,但我有尝试获取查询本身的当前索引的问题。
换句话说,使用@each指令,我需要能够访问正在呈现的部分中的当前循环的键(或索引)。
如果您有任何需要了解的信息,请询问。
感谢您阅读!
答案 0 :(得分:4)
查看为@each
指令运行的源代码会产生以下结果:
照亮\视图\ Factory.php
/**
* Get the rendered contents of a partial from a loop.
*
* @param string $view
* @param array $data
* @param string $iterator
* @param string $empty
* @return string
*/
public function renderEach($view, $data, $iterator, $empty = 'raw|')
{
$result = '';
// If is actually data in the array, we will loop through the data and append
// an instance of the partial view to the final result HTML passing in the
// iterated value of this data array, allowing the views to access them.
if (count($data) > 0) {
foreach ($data as $key => $value) {
$data = ['key' => $key, $iterator => $value];
$result .= $this->make($view, $data)->render();
}
}
// If there is no data in the array, we will render the contents of the empty
// view. Alternatively, the "empty view" could be a raw string that begins
// with "raw|" for convenience and to let this know that it is a string.
else {
if (Str::startsWith($empty, 'raw|')) {
$result = substr($empty, 4);
} else {
$result = $this->make($empty)->render();
}
}
return $result;
}
如果你注意到这些方面:
$data = ['key' => $key, $iterator => $value];
$result .= $this->make($view, $data)->render();
名为$key
的变量会自动传递给渲染视图。那应该包含数组循环的当前索引。