在項目開發過程中會遇到一個網站有不同風格,本文詳細介紹Thinkphp5 實現模板主題多個模板切換
一、在Config中配置view_path模板路徑代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
'template'
=> [
// 模板引擎類型 支持 php think 支持擴展
'type'
=>
'Think'
,
// 模板路徑
'view_path'
=>
'/template/'
,
// 模板后綴
'view_suffix'
=>
'html'
,
// 模板文件名分隔符
'view_depr'
=> DS,
// 模板引擎普通標簽開始標記
'tpl_begin'
=>
'{'
,
// 模板引擎普通標簽結束標記
'tpl_end'
=>
'}'
,
// 標簽庫標簽開始標記
'taglib_begin'
=>
'{'
,
// 標簽庫標簽結束標記
'taglib_end'
=>
'}'
,
],
|
二、所有控制器繼承 Base控制器,Base 控制器代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class
Base
extends
Controller
{
public
function
__construct(Request
$request
)
{
if
(
$request
->isMobile())
{
config(
'template.view_path'
,
'template/default/mobile/'
.
$request
->module().
"/"
);
}
else
{
config(
'template.view_path'
,
'template/default/web/'
.
$request
->module().
"/"
);
}
parent::__construct(
$request
);
}
}
|
PS:必須在構造函數里用config,構造函數過后調用就沒用了
====================================
以上是全局切換,下面 是自定義切換
====================================
1.無參數調用
return $view->fetch();
2.指定操作調用
return $view->fetch("index");
3.帶控制器
return $view->fetch("demo/index");
4.跨模塊調用
return $view->fetch("admin@demo/index");
5.全路徑模板調用
return $view->fetch(APP_PATH.request()->module().'/view/demo/index.html');
采用5,全路徑模板調用可解決