2021-11-11 18:16 ThinkPHP 74 梁俊威
最近在研究TP6的东西,想着做一个后台管理系统,但是遇到一个问题难到我了,我从前的开发习惯是将一个后台分为多个模块去进行开发,因此需要跨应用去进行继承模板的操作,可官方文档没有明确表示,于是我打算将计就计去采用TP5所传承的风格,这样去继承:
{extend name="admin@layout/layout"}
可是令我惊讶的是,他并没有什么作用!!!这TP5的优良没传承下来?
我找了很多办法,最后还是选择了自己修改底层代码,奉上修改思路。
我去看了TP5的视图模板继承底层,是这样的
然后废话不多说,就开始上代码吧!
// 找到根目录下\vendor\topthink\think-template\src\Template.php
为模板配置参数添加一个“view_base”的变量
通过CTRL+F查找parseTemplateFile方法,将其源码修改成:
private function parseTemplateFile(string $template): string { // 跨应用获取视图模板 if (strpos($template, '@')) { $base = $this->config['view_base']; $temp = explode('@', $template); $temp[1] = str_replace( "/", "\\", $temp[1]); $template = $base.$temp[0]."\\template\\".$temp[1].".".$this->config['view_suffix']; }else{ if ('' == pathinfo($template, PATHINFO_EXTENSION)) { if (0 !== strpos($template, '/')) { $template = str_replace(['/', ':'], $this->config['view_depr'], $template); } else { $template = str_replace(['/', ':'], $this->config['view_depr'], substr($template, 1)); } $template = $this->config['view_path'] . $template . '.' . ltrim($this->config['view_suffix'], '.'); } } if (is_file($template)) { // 记录模板文件的更新时间 $this->includeFile[$template] = filemtime($template); return $template; } throw new Exception('template not exists:' . $template); }
TIPS:
找到根目录文件\vendor\topthink\think-view\src\Think.php,搜索fetch方法,将其修改成:
public function fetch(string $template, array $data = []): void { if (empty($this->config['view_path'])) { $view = $this->config['view_dir_name']; if (is_dir($this->app->getAppPath() . $view)) { $path = $this->app->getAppPath() . $view . DIRECTORY_SEPARATOR; } else { $appName = $this->app->http->getName(); $path = $this->app->getRootPath() . $view . DIRECTORY_SEPARATOR . ($appName ? $appName . DIRECTORY_SEPARATOR : ''); } /* 重点是修改这里 */ $this->config['view_path'] = $path; $base = $this->app->getBasePath(); $this->config['view_base'] = $base; $this->template->view_path = $path; $this->template->view_base = $base; /* 重点是修改这里 */ } if ('' == pathinfo($template, PATHINFO_EXTENSION)) { // 获取模板文件名 $template = $this->parseTemplate($template); } // 模板不存在 抛出异常 if (!is_file($template)) { throw new TemplateNotFoundException('template not exists:' . $template, $template); } $this->template->fetch($template, $data); }
大致的原理就是:“将app目录地址传递进需要查询的模板文件中,将模板文件地址引用为正确的地址”,希望能够帮到大家
若无特殊说明,本站点所有内容均为原创,转载请说明出处!