CI框架设置Layout布局

来源:互联网 发布:怎么样使用淘宝助理 编辑:程序博客网 时间:2024/06/07 02:00

在使用CI的过程中,发现没有很好的布局使用,而如果每个文件都手工添加有太浪费时间和效率,回顾以前的项目记得曾经做过CI的layout的设置,

网上查找下还真找到了。。记录下使用技巧,以后有项目也可以参考使用。

首先定义全局的Controller,在项目的applcation/core目录下定义自己的Controller,不过要使用MY_开头也就是必须命名为:MY_Controller当然也可以自己

在config.php中修改 $config['subclass_prefix'] = 'MY_';的内容为自己项目名称,网上也有很多把layout单独开发作为类库加载的,就是单独做了

Library下的文件Layout.php 不过需要在autoload中指定自动加载,可以根据自己爱好选择。。这里只介绍自定义全局控制器方法实现. 

一、在application/core目录下定义MY_Controller内容如下: 

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');    class MY_Controller extends CI_Controller    {        protected $layout = 'layout/main';        private   $js_files = array();        private   $css_files = array();        public    $need_login = false;        public function __construct()        {            parent::__construct();            //$this->check_login();        }        public function add_js($filepath)        {            array_push($this->js_files, "<script type='text/javascript' src='". $filepath ."'></script>");        }        public function add_css($filepath){              array_push($this->css_files, "<link href='".$filepath."' rel='stylesheet' type='text/css'>");        }        protected function render($file = NULL, $viewData = array(), $globalData= array())        {            if($this->js_files){                $globalData['js_files'] = $this->js_files;            }            if($this->css_files){                $globalData['css_files'] = $this->css_files;             }            if( !is_null($file) ) {                $data['content'] = $this->load->view($file, $viewData, TRUE);                $data['layout'] = $globalData;                $this->load->view($this->layout, $data);            } else {                $this->load->view($this->layout, $viewData);            }            $viewData = array();        }   }


其中css_files和js_files用来渲染js和css文件,这里还没有实现后续需要会逐步完善。

二、在layout下建立 main.php文件,内容如下

<html>    <head>    <title><?php echo $layout['title'];?></title>    </head>    <body>        <?php echo $content?>    </body></html>

三、使用

在自定义controller中继承自MY_Controller,添加比如下面测试代码:

    public function layout(){            $data= array('user_name'=>'张三','password'=>'密码');            $this->render('test_layout',$data,array('title'=>'测试布局'));        }
这样视图会首先渲染test_layout中的数据,然后把数据作为内容传递给父视图中。test_layout.php代码如下

<h1><?php echo $user_name;?></h1>
效果图: 


实现其实并不复杂,关键是这样的思想和设计方法。。。


0 0
原创粉丝点击