以下是在Ubuntu上使用ThinkPHP模板引擎的核心技巧,结合搜索资源中的关键信息整理:
安装与项目创建
composer create-project topthink/think tp
public
文件夹。模板文件结构
application/view
目录,后缀为.html
。assign()
传递数据到模板,支持数组批量赋值:$this->assign(['title' => '首页', 'list' => $data]);
return $this->fetch('index'); // 渲染index.html
布局继承
layout/base.html
),使用{block}
标签标记可替换区域:<html>
<head><block name="title">默认标题</block></head>
<body>
<div class="header">{include file="public/header" /}</div>
<div class="content">{block name="content"}默认内容{/block}</div>
</body>
</html>
{extend}
继承布局,并重写{block}
内容:{extend name="layout/base" /}
{block name="title"}用户列表 - {$web_title}{/block}
{block name="content"}
<table>{volist name="list" id="user"}<tr><td>{$user.id}</td><td>{$user.name}</td></tr>{/volist}</table>
{/block}
组件化包含
{include}
引入公共模块(如头部、底部):{include file="public/header" /} <!-- 引入header.html -->
变量输出
{$变量名}
,支持对象属性(如{$user.name}
)。{$变量|default='无数据'}
。流程控制
{if $status == 1}<p>启用</p>{else}<p>禁用</p>{/if}
{volist name="list" id="item"}<li>{$item.id}</li>{/volist}
{foreach name="data" item="value"}<p>{$value.key}</p>{/foreach}
缓存配置
APP_DEBUG=true
),生产环境开启:// config/view.php
'cache' => true, // 开启模板缓存
'cache_time' => 3600, // 缓存时间(秒)
php think clear
。减少模板复杂度
{include}
和{extend}
,减少重复代码。路径问题
application/view
的相对路径。sudo chmod -R 755 application/view
。依赖管理
composer require topthink/think-template
。.env
文件,设置APP_DEBUG=true
,查看模板解析错误。php think make:controller
快速生成控制器,搭配模板生成器提升效率。以上技巧综合自,可根据项目需求灵活应用。