CodeIgniter + smarty 實現widget功能

在開發過程當中,常常須要widget功能,一能夠隔離頁面邏輯,二能夠重用代碼。結合smarty的plugin功能,能夠方便的實現該功能。php

譬如,咱們的頁面中能夠這樣寫:html

{{extends file='_layout.html'}} 

{{block name='content'}}

<!--content-->
<div>
    <div>
        {{widgets path='widgets/carousel'}}
        {{widgets path='widgets/news'}}
    </div>
    {{widgets path='widgets/hots'}}
    {{widgets path='widgets/tops'}}
</div>
<!--/content-->

{{/block}}

{{widgets path='widgets/news'}}表示調用widgets Controller 的news action,最終輸出的html嵌入這裏。ui

須要實現該功能,能夠藉助smarty 的function plugin,建立一個 function.widgets.phpspa

<?php
function smarty_function_widgets($params,&$smarty){
        
    $path = $params['path'];
    $args = isset($params['args']) ? $params['args'] : NULL;
    
    if($path){
        $ps = explode('/', $path);
        
        $controller = $ps[0];
        $method = $ps[1];
        
        require_once APPPATH.'controllers/'.$controller.'.php';
                
        $c = new $controller;
        
        if(!isset($params['args']))
            $c->$method();
        else
            $c->$method($args);
    }
}

?>
相關文章
相關標籤/搜索