CodeIgniter默认布局问题:如何在CodeIgniter_2.0.2中为整个项目创建默认布局?
I want to create a default layout for whole codeigniter project. (like cakephp)
I also need to pass value from database (through controller) to default layout.
How can i do this ?
我想为整个codeigniter项目创建一个默认布局。 (比如cakephp) p>
我还需要将值从数据库(通过控制器)传递到默认布局。 p>
我该怎么做? p> div>
You can use the hooks to achieve this
post_controller - You can set vars with this.
Called immediately after your controller is fully executed.
display_override - You can override display and include your own view.
Overrides the _display() function, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output()
reference : http://codeigniter.com/user_guide/general/hooks.html
The CodeIgniter wiki is a great place to look for this type of help.
For example, here are four different approaches to achieve what you want to do.
Actually there's a very simple solution that you can use. This is a micro-library that I have written for using layouts in CodeIgniter :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Layout {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
/**
* This method loads either the default layout (defined in the config.php file with the key default_layout) or a specific layout
* @param string $view
* @param array $params
* @param string $layout
*/
public function load_layout($view, $params = array(), $layout = "") {
// get the name of the layout file
$layout_file = file_exists(dirname(__FILE__) . "../views/" . $layout) ? $layout : $this->CI->config->item("default_layout");
// load it, transmit the params
$this->CI->load->view(
$layout_file,
array(
"view_name" => $view,
"view_params" => $params
)
);
}
?>
Add this file to your project in a Layout.php file, then just go to your config file and add the following line :
$config['default_layout'] = "your-default-layout-name.php";
And finally create a new file into the application/views folder of your project and name it with the value you put into your config file i.e. your-default-layout-name.php. Paste all the contents of the basic structure of your pages and add in the main wrapper :
<?php
// load required view
if (isset($view_name)) {
$this->load->view(
$view_name, $view_params
);
}
?>
Okay ! now you can simply replace the native :
$this->load->view("view-name.php", $params);
by :
// load the default layout
$this->layout->load_layout("view-name.php", $params);
// load a specific layout
$this->layout->load_layout("view-name.php", $params, "my-specific-layout.php");
And it will work like a charm !
Note: do not forget to include the library, either in you autoload.php file or directly in your script.