laravel 5 實現模板主題功能_php執行個體

來源:互聯網
上載者:User
眾所周知,laravel渲染模板是通過View::make()實現的,需要顯式指定模板檔案路徑:

複製代碼 代碼如下:
function index()
{
return View::make('index.index');
}

既然這樣,我們就可以自己實現模板主題功能,我們只需要將模板檔案放到一個主題名稱對應的目錄裡就行,比如預設主題為 default 的話,我們就這樣寫:

複製代碼 代碼如下:
function index()
{
return View::make('default.index.index');
}

自訂佈景主題 custom :

複製代碼 代碼如下:
function index()
{
return View::make('custom.index.index');
}

從設定檔中讀取主題名:

複製代碼 代碼如下:
function index()
{
return View::make(Config::get('app.theme','default').'.index.index');
}

這樣基本就實現模板主題化的功能了,但還存在一個問題,那就是custom主題必須實現所有default主題的所有模板,否則會導致某些頁面模板檔案不存在報錯,那麼進一步最佳化:

複製代碼 代碼如下:
function index()
{
$theme = Config::get('app.theme','default');
$tpl = $theme.'.index.index';
if (!View::exists($tpl)) {
$tpl = 'default.index.index';
}
return View::make($tpl);
}

就是在渲染模板之前,先檢測模板檔案是否存在,不存在的話則使用default主題中對應的模板。

這麼多行代碼,我們可以繼續封裝一下,這時候要用到Response對象了,我們知道 Response::view() 等同於 View::make(),而Response還有一個方法Response::macro()方法可以用來定義一個宏,我們可以把邏輯封裝到宏裡面:

複製代碼 代碼如下:
Response::macro('render',function($path,$data=array()){
$theme = Config::get('app.theme','default');
$tpl = $theme.'.'.$path;
if (!View::exists($tpl)) {
$tpl = 'default.' . $path;
}
return Response::view($tpl,$data);
});

使用:

複製代碼 代碼如下:
function index()
{
$bindings = array(
'title' => '首頁'
);
return Response::render('index.index',$bindings);
}

需要注意的是傳入模板的變數得通過Response::render的第二個參數。

今天的教程就先到這裡吧,後續我們再來深入分析一下,希望大家能夠喜歡。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.