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.

php Courses
php Courses
php Courses
Using volist and foreach tags for array loops in ThinkPHP6 templates

ThinkPHP6 provides two template tags, volist and foreach, for looping over arrays in view files.

volist tag

Syntax:

{volist name="" id="" key="" offset="" length=""}
    // loop body
{/volist}

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:

<?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();
    }
}
?>

Template usage:

{volist name="arr" id="vv" key="kk" offset="1" length="1"}
    <div>{$kk} --- {$vv['name']}</div>
{/volist}

The output shows only the second element ("cctv") because the loop starts at offset 1 and retrieves one record.

foreach tag

Syntax:

{foreach $name as $key=>$id}
    // loop body
{/foreach}

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:

{foreach $arr as $k=>$v}
    <div>{$k} --- {$v['name']}</div>
{/foreach}

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendforeachThinkPHP6volist
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.