主题:
foreach和volist标签实现数据库中的记录在网页中分页显示。
实现效果:
foreach分页
volist分页
控制器(index/controller/Car.php)实例
<?php namespace app\index\controller; use think\Controller; use app\index\model\Car as CarModel; class Car extends Controller { // 分页 public function pages() { // 分页配置 $config = [ 'type' => 'bootstrap', 'var_page' => 'page' ]; // 每个分页显示数量 $num = 5; // 是否简单分页 $simple = false; // 用模型获取所有分页数量:think\paginate $paginate = CarModel::paginate($num, $simple, $config); // 渲染分页html,返回分页变量(生成html代码) $page = $paginate->render(); // 将分页数据赋值给模板 $this->view->assign('cars', $paginate); // 将分页变量赋值给模板 $this->view->assign('page', $page); // 渲染模板(将生成的html代码编译到网页中显示) return $this->view->fetch(); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
模板(index/view/car/pages.html)实例
{load href="/static/bootstrap/css/bootstrap.min.css"} <div class="container"> <div class="row"> <h3 class="text-center">车辆信息表</h3> <div class="col-md-8 col-md-offset-2"> <table class="table table-bordered table-hover text-center"> <tr class="info"> <th class="text-center">ID</th> <th class="text-center">名称</th> <th class="text-center">型号</th> <th class="text-center">颜色</th> <th class="text-center">价格</th> <th class="text-center">创建时间</th> <th class="text-center">更新时间</th> <th class="text-center">删除时间</th> </tr> {//foreach $cars as $car} <!-- <tr> <td>{//$car.car_id}</td> <td>{//$car.car_name}</td> <td>{//$car.car_type}</td> <td>{//$car.car_color}</td> <td>{//$car.price} {//in name="car.price" value="100000,500000"} {//if $car.price == 100000} 10万 {//else /} 50万 {///if} {///in} </td> <td>{//$car.create_time}</td> <td>{//$car.update_time}</td> <td>{//$car.delete_time}</td> </tr> --> {///foreach} {volist name="cars" id="car"} <tr> <td>{$car.car_id}</td> <td>{$car.car_name}</td> <td>{$car.car_type}</td> <td>{$car.car_color}</td> <td>{$car.price}</td> <td>{$car.create_time}</td> <td>{$car.update_time}</td> <td>{//$car.delete_time} {between name="car.delete_time" value="0,1"} 正常 {/between} {between name="car.delete_time" value="2,99999999999"} 已删除 {/between} </td> </tr> {/volist} </table> <div class="text-center">{$page|raw}</div> </div> </div> </div> {load href="/static/jquery-3.2.1/jquery-3.2.1.min.js"} {load href="/static/bootstrap/js/bootstrap.min.js"}
运行实例 »
点击 "运行实例" 按钮查看在线实例
模型(index/model/Car.php)实例
<?php namespace app\index\model; use think\Model; class Car extends Model { protected $table = 'car'; protected $pk = 'car_id'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
知识点:
分页类是抽象类,无法直接实例化,需要继承在子类中实例化;
thinkphp5.1.14中使用bootstrap为分页默认前端框架,如果要自定义,自己写分页类放到thinkphp/library/paginator/driver下,并继承paginator
模板标签{in}:枚举,离散值
模板标签{between}:连续数据