@Reinis 对于低于 2.0 的旧版本 CI 的回答可能正确,但从那时起发生了很多变化,所以我想我会用我所做的最新方法来回答这个问题。
大部分和@Reinis方法类似,这里也有描述:http://codeigniter.com/wiki/MY_Controller_-_how_to_extend_the_CI_Controller
但是这里是我所做的更新:
第1步:创建一个MY_Controller.php文件并将其存储在/application/core中
第 2 步:在您的 MY_Controller.php 文件中输入以下内容:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function _output($content)
{
// Load the base template with output content available as $content
$data['content'] = &$content;
echo($this->load->view('base', $data, true));
}
}
第 3 步:创建一个基于 MY_Controller.php 的示例控制器,在这种情况下,我将在 application/controllers/ 中创建一个 welcome.php 控制器,其内容如下:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
}
设置这些控制器后,请执行以下操作:
第四步:在 /application/views 中创建一个基础视图,并将文件命名为 base.php,文件的内容应该类似于:
<!DOCTYPE html>
<!--[if IE 7 ]><html lang="en" class="ie7"><![endif]-->
<!--[if IE 8 ]><html lang="en" class="ie8"><![endif]-->
<!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title></title>
<link rel="stylesheet" href="<?php echo base_url(); ?>stylesheets/reset.css" media="screen" />
</head>
<body>
<div id="section_main">
<div id="content">
<?php echo $content; ?>
</div>
</div>
<?php $this->load->view('shared/scripts.php'); ?>
</div>
</body>
</html>
第5步:在/application/views中创建另一个视图并将这个视图命名为welcome_message.php,这个文件的内容是:
<h1>Welcome</h1>
一旦完成,您应该会看到以下输出:
<!DOCTYPE html>
<!--[if IE 7 ]><html lang="en" class="ie7"><![endif]-->
<!--[if IE 8 ]><html lang="en" class="ie8"><![endif]-->
<!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title></title>
<link rel="stylesheet" href="http://somedomain.local/stylesheets/reset.css" media="screen" />
</head>
<body>
<!-- BEGIN: section_main -->
<div id="section_main">
<div id="content">
<h1>Welcome</h1>
</div>
</div>
<!-- END: section_main -->
<script src="/path/to/js.js"></script>
</div>
</body>
</html>
如您所见,<h1>Welcome</h1> 已放入基本模板中。
资源:
希望这可以帮助其他遇到这种技术的人。