我很久以前找到了一篇文章,但我现在似乎找不到它,基本上是作者(我忘记了)覆盖了输出的显示。这种输出方法将访问您对给定controller/method 的视图,并尝试自动在您的视图目录中搜索。
使用风险自负
Application/core/MY_COntroller.php
------------------------------------------ --------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
------------------------------------------ --------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
这是我用来创建我的模板的。基本上你需要一个目录结构如下。
+观看次数
|+布局
||-layout.php
layout.php 将作为您的主模板
如何使用?
扩展控制器
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
只需在您的视图中创建目录并用控制器名称命名,即 user 然后在其中添加一个您命名为方法的文件,即 create_user
所以现在你的目录结构将是
+观看次数
| +布局
| |-layout.php
| |-second_master_layout.php
| +用户
| |-create_user.php
只需编辑代码即可为您提供动态的header 或footer