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 ?
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
You can consider using a template system. For example Template library
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.
精彩评论