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

?>
相关文章
相关标签/搜索