許多 CMS 系統支援「一鍵換膚」,Laravel 5 如何優雅實現?本文從最直觀的路徑前綴法起步,逐步優化至「存在性檢查回退」與「Response Macro 封裝」,提供可直接落地的代碼方案。
Laravel 渲染視圖需顯式指定路徑 View::make('path.to.view')。最直接的想法是將主題名作為路徑前綴:
// 預設主題
return View::make('default.index.index');
// 自訂主題
return View::make('custom.index.index');
將主題名存入 config/app.php:
'theme' => 'default',
控制器中動態拼接:
function index() {
return View::make(config('app.theme', 'default') . '.index.index');
}
自訂主題往往僅覆蓋部分頁面,缺失模板時應自動使用預設主題對應模板,避免 FileNotFoundException:
function index() {
$theme = config('app.theme', 'default');
$tpl = $theme . '.index.index';
if (!View::exists($tpl)) {
$tpl = 'default.index.index'; // 回退
}
return View::make($tpl);
}
在 App\Providers\AppServiceProvider::boot() 或 bootstrap/app.php 註冊巨集:
Response::macro('render', function ($path, $data = []) {
$theme = config('app.theme', 'default');
$tpl = $theme . '.' . $path;
if (!View::exists($tpl)) {
$tpl = 'default.' . $path;
}
return Response::view($tpl, $data);
});
控制器調用極度簡潔:
function index() {
return Response::render('index.index', ['title' => '首頁']);
}
$data 傳遞,不可依賴 View::share() 全域共享(除非刻意)。View::exists() 會觸發文件系統檢查,高流量場景建議快取主題模板映射表。@extends 繼承佈局,子模板路徑同樣需帶主題前綴,或在佈局中使用相對路徑。此方案零侵入核心、相容既有專案、支援無限級主題擴展,是中小型專案快速實現多主題的最佳平衡點。