linux

Linux下ThinkPHP模板引擎使用教程

小樊
40
2025-10-14 01:44:24
栏目: 编程语言

Linux下ThinkPHP模板引擎使用教程

一、基础准备

1. 环境要求

确保Linux系统已安装PHP 7.4+Composer及ThinkPHP框架(推荐ThinkPHP 6.x,兼容性好且功能完善)。可通过以下命令验证环境:

php -v
composer -V

2. 目录结构

ThinkPHP的模板文件默认存放在/application/[模块名]/view/目录下(如/application/index/view/)。建议按模块划分视图文件夹,例如:

/application
  /index
    /view
      /home
        index.html  # 首页模板
      /user
        profile.html  # 用户资料模板

3. 控制器渲染基础

在控制器中,通过assign()方法传递数据,fetch()方法渲染模板。例如/application/index/controller/Index.php

<?php
namespace app\index\controller;
use think\Controller;

class Index extends Controller
{
    public function index()
    {
        // 传递单个变量
        $this->assign('title', 'Linux下ThinkPHP模板使用教程');
        
        // 传递数组数据
        $data = [
            'content' => '本教程将指导你在Linux环境下使用ThinkPHP模板引擎',
            'version' => 'ThinkPHP 6.x'
        ];
        $this->assign($data);
        
        // 渲染模板(默认查找/application/index/view/index/index.html)
        return $this->fetch();
    }
}

fetch()方法的参数为模板文件路径(省略模块名和后缀),框架会自动定位到对应目录。

二、模板语法详解

ThinkPHP 6.x默认使用Twig模板引擎(扩展了ThinkPHP原生标签),语法更灵活。以下是常用语法:

1. 变量输出

使用{{ }}包裹变量名(无需$符号):

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>  <!-- 输出控制器传递的$title变量 -->
</head>
<body>
    <h1>{{ content }}</h1>  <!-- 输出$data['content'] -->
    <p>框架版本:{{ version }}</p>  <!-- 输出$data['version'] -->
</body>
</html>

2. 流程控制

if条件判断

{% if isLogin %}
    <a href="/logout">退出登录</a>
{% else %}
    <a href="/login">登录</a>
{% endif %}

foreach循环

<ul>
    {% for article in articles %}
        <li>
            <h3>{{ article.title }}</h3>
            <p>{{ article.content }}</p>
        </li>
    {% endfor %}
</ul>

articles为控制器传递的数组(如$this->assign('articles', $articleList))。

3. 模板继承

通过{extend}继承父模板,{block}重写子模板内容:

父模板(/application/index/view/layout/base.html)

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}默认标题{% endblock %}</title>
</head>
<body>
    <div class="header">
        <h1>网站LOGO</h1>
    </div>
    
    <div class="content">
        {% block content %}{% endblock %}  <!-- 子模板替换此处内容 -->
    </div>
    
    <div class="footer">
        <p>© 2025 Linux下ThinkPHP模板引擎教程</p>
    </div>
</body>
</html>

子模板(/application/index/view/home/index.html)

{extend name="layout/base"}  <!-- 继承父模板 -->

{% block title %}首页 - {{ title }}{% endblock %}  <!-- 重写标题 -->

{% block content %}
    <h2>欢迎来到首页</h2>
    <p>{{ content }}</p>
    
    <!-- 引入子模板(如header/footer) -->
    {% include "home/header.html" %}
    
    <ul>
        {% for article in articles %}
            <li>{{ article.title }}</li>
        {% endfor %}
    </ul>
    
    {% include "home/footer.html" %}
{% endblock %}

4. 内置函数与过滤器

调用PHP函数

使用{{ }}包裹函数调用(如日期格式化):

<p>当前时间:{{ "now"|date("Y-m-d H:i:s") }}</p>

date为PHP内置函数,"now"为时间标识符。

过滤器(Escape)

使用|符号应用过滤器(如转义HTML,防止XSS攻击):

<p>用户名:{{ username|htmlspecialchars }}</p>

常用过滤器upper(转大写)、lower(转小写)、default(默认值,如{{ name|default('游客') }})。

三、常用功能实践

1. 模板缓存

模板缓存可提升性能,需在config/view.php中配置:

return [
    'cache' => true,          // 开启缓存
    'cache_time' => 3600,     // 缓存时间(秒)
    'tpl_cache' => true,      // 模板缓存开关
];

清除缓存:通过命令行或代码清除:

php think clear  # 清除所有缓存(包括模板缓存)

或代码中清除:

use think\facade\Cache;
Cache::clear();  // 清除模板缓存

2. 自定义模板标签

若需扩展原生标签,可通过继承think\Template类实现。例如创建/application/common.php

<?php
use think\Template;

// 自定义标签:格式化日期
Template::hook('tpl_begin', function() {
    Template::createTag('formatDate', function($params) {
        $timestamp = $params['timestamp'] ?? time();
        return date('Y-m-d', $timestamp);
    });
});

模板中使用:

<p>创建时间:{{ {'timestamp': item.create_time}|formatDate }}</p>

3. 包含子模板

使用{% include %}引入公共模板(如头部、尾部):

<!-- 引入header模板 -->
{% include "common/header.html" %}

<!-- 页面主体内容 -->
<div class="main">
    {{ content }}
</div>

<!-- 引入footer模板 -->
{% include "common/footer.html" %}

:子模板路径相对于当前模块的view目录。

四、注意事项

  1. 权限问题:确保Linux下/application/view/目录有读写权限(建议chmod -R 755 /application/view/)。
  2. 路径规范:模板文件路径需与控制器模块、控制器名、方法名对应(如Index控制器的index方法对应/application/index/view/index/index.html)。
  3. 调试技巧:开启调试模式(config/app.php'app_debug' => true),可查看模板渲染错误信息。
  4. 性能优化:生产环境下关闭模板调试('app_debug' => false),并开启模板缓存。

通过以上步骤,你可在Linux环境下熟练使用ThinkPHP模板引擎,实现业务逻辑与视图层的分离,提升开发效率。

0
看了该问题的人还看了