Using volist and foreach tags for array loops in ThinkPHP6 templates
This article explains how to use ThinkPHP6's volist and foreach template tags to iterate over arrays, detailing their syntax, attributes, example PHP code, and the differences in how each tag handles variable references and output.
ThinkPHP6 provides two template tags, volist and foreach , for looping over arrays in view files.
volist tag
Syntax:
<code>{volist name="" id="" key="" offset="" length=""}
// loop body
{/volist}</code>Attributes:
name : the variable name of the array passed to the template.
id : the variable representing each item in the loop.
key : the index, default starts at 1.
offset : the starting row number.
length : the number of rows to retrieve.
Example PHP code defining an array and assigning it to the view:
<code><?php
namespace app\controller;
use think\facade\View;
class Test {
public function index(){
$arr = [
['id'=>1,'name'=>'cmcc'],
['id'=>2,'name'=>'cctv'],
['id'=>1,'name'=>'cmqq']
];
View::assign('arr', $arr);
return View::fetch();
}
}
?></code>Template usage:
<code>{volist name="arr" id="vv" key="kk" offset="1" length="1"}
<div>{$kk} --- {$vv['name']}</div>
{/volist}</code>The output shows only the second element ("cctv") because the loop starts at offset 1 and retrieves one record.
foreach tag
Syntax:
<code>{foreach $name as $key=>$id}
// loop body
{/foreach}</code>Attributes:
name : the variable name of the array in the template.
id : the variable representing each item.
key : the index, default starts at 0.
Example template usage:
<code>{foreach $arr as $k=>$v}
<div>{$k} --- {$v['name']}</div>
{/foreach}</code>The result lists all array elements with their indices. The article notes that the foreach tag requires a leading $ for variable names, whereas volist does not.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.