欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

laravel 5 實(shí)現(xiàn)模板主題功能

 更新時(shí)間:2015年03月02日 14:29:16   投稿:hebedich  
很多cms里都有模板主題功能,我們可以通過一個(gè)配置切換主題,這個(gè)功能在laravel下如何實(shí)現(xiàn)呢?今天我們就來探討下這個(gè)問題。

眾所周知,laravel渲染模板是通過View::make()實(shí)現(xiàn)的,需要顯式指定模板文件路徑:

復(fù)制代碼 代碼如下:

function index()
{
    return View::make('index.index');
}

既然這樣,我們就可以自己實(shí)現(xiàn)模板主題功能,我們只需要將模板文件放到一個(gè)主題名稱對(duì)應(yīng)的目錄里就行,比如默認(rèn)主題為 default 的話,我們就這樣寫:

復(fù)制代碼 代碼如下:

function index()
{
    return View::make('default.index.index');
}

自定義主題 custom :

復(fù)制代碼 代碼如下:

function index()
{
    return View::make('custom.index.index');
}

從配置文件中讀取主題名:

復(fù)制代碼 代碼如下:

function index()
{
    return View::make(Config::get('app.theme','default').'.index.index');
}

這樣基本就實(shí)現(xiàn)模板主題化的功能了,但還存在一個(gè)問題,那就是custom主題必須實(shí)現(xiàn)所有default主題的所有模板,否則會(huì)導(dǎo)致某些頁面模板文件不存在報(bào)錯(cuò),那么進(jìn)一步優(yōu)化:

復(fù)制代碼 代碼如下:

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

就是在渲染模板之前,先檢測(cè)模板文件是否存在,不存在的話則使用default主題中對(duì)應(yīng)的模板。

這么多行代碼,我們可以繼續(xù)封裝一下,這時(shí)候要用到Response對(duì)象了,我們知道 Response::view() 等同于 View::make(),而Response還有一個(gè)方法Response::macro()方法可以用來定義一個(gè)宏,我們可以把邏輯封裝到宏里面:

復(fù)制代碼 代碼如下:

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);
});

使用:

復(fù)制代碼 代碼如下:

function index()
{
    $bindings = array(
        'title' => '首頁'
    );
    return Response::render('index.index',$bindings);
}

需要注意的是傳入模板的變量得通過Response::render的第二個(gè)參數(shù)。

今天的教程就先到這里吧,后續(xù)我們?cè)賮砩钊敕治鲆幌?,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論