thinkphp 8.0 默认不支持 blade 模板语法,直接写@if或{{ $name }}会原样输出或报错;必须手动集成illuminate/view:^10.0并重写渲染流程,且需确认view配置中'type' => 'think'已启用thinktemplate引擎作为基础支撑。

ThinkPHP 8.0 默认不支持 Blade 模板语法,直接写 @if 或 {{ $name }} 会原样输出或报错,必须手动集成 Laravel 的 Blade 组件并重写渲染流程才能启用。
确认当前模板引擎状态
打开 config/view.php,检查 'type' => 'Think' 是否存在;若不存在或值为 'php',说明未启用 ThinkTemplate 引擎,Blade 集成将失去基础支撑。
运行 php think version 确认是 TP8 正式版(非 RC 或 dev 分支),否则 think\view\driver\Engine 接口可能不稳定。
安装 Blade 渲染组件
在项目根目录执行:composer require illuminate/view:^10.0(必须指定 ^10.0,低版本不兼容 PHP 8.2+)。
安装后检查 vendor/illuminate/view/Factory.php 是否存在,缺失则 Composer 安装失败,需清缓存重试:composer clear-cache && composer install。
【注意】不要安装 laravel/framework 全量包——它会引入 HTTP、队列等冗余组件,导致自动加载变慢且冲突风险激增。
注册 Blade 驱动类
在 app/provider/ 目录下新建 BladeServiceProvider.php:
内容为:
<?php namespace app\provider;use think\Service;use Illuminate\View\Factory as BladeFactory;use Illuminate\View\Engines\CompilerEngine;use Illuminate\View\Engines\PhpEngine;use Illuminate\View\Engines\ChainEngine;use Illuminate\View\Compilers\BladeCompiler;use Illuminate\Filesystem\Filesystem;class BladeServiceProvider extends Service{ public function register() { $this->app->bind('blade.compiler', function ($app) { $compiler = new BladeCompiler(new Filesystem(), config('view.compiled')); $compiler->setCachePath(config('view.compiled')); return $compiler; }); $this->app->bind('view.engine.resolver', function ($app) { $resolver = new \Illuminate\View\Engines\EngineResolver(); $resolver->register('blade', function () use ($app) { return new CompilerEngine($app->make('blade.compiler')); }); $resolver->register('php', function () { return new PhpEngine(); }); return $resolver; }); }}
配置 view.php 启用 Blade
修改 config/view.php 中的以下三项:
'type' => 'blade',
'view_suffix' => 'blade.php',
'compiled' => runtime_path('view'),
【关键】'type' 必须设为字符串 'blade',且小写,框架据此加载对应驱动;设为 'Blade' 或 'BLADE' 将静默回退到 php 引擎,{$var} 仍可工作但 @if 失效。
确保 runtime/view 目录存在且可写,否则编译时抛出 file_put_contents(): Failed to open stream 错误。
创建 Blade 模板文件
在 app/view/ 下新建 index.blade.php,内容为:
@extends('layouts.app')@section('content')<h1>Hello, {{ $name }}</h1>@endsection
Blade 模板必须以 .blade.php 为后缀,否则 view('index') 无法匹配——TP8 不再尝试后缀推导,view_suffix 是唯一依据。
父模板 layouts/app.blade.php 必须包含 @yield('content'),否则子模板内容不会被注入,页面为空白。
控制器中调用 Blade 模板
第一步:在控制器顶部添加 use think\facade\View;;
第二步:在操作方法中写 return View::fetch('index', ['name' => 'ThinkPHP']);;
第三步:确保该控制器继承 think\Controller,否则 View::fetch() 调用时会因找不到上下文而报 Call to a member function make() on null。
这一步操作起来很简单,直接把数组传进去就行。但要注意:Blade 模板里不能混用 ThinkPHP 的 {volist} 标签,它们由不同引擎解析,共存会导致编译中断。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











