CodeIgniter's default view loading process requires the repetitive task of including header and footer views in every controller. This can become tedious and time-consuming when working with multiple controllers and views.
To address this issue, a custom loader class can be created to automate the process of including header and footer views. This allows developers to load views without explicitly calling the load->view() method for each component.
Create a new file named MY_Loader.php in the application/core directory. This file will extend the CodeIgniter's CI_Loader class and add a new template() method.
<code class="php">// application/core/MY_Loader.php class MY_Loader extends CI_Loader { public function template($template_name, $vars = array(), $return = FALSE) { $content = $this->view('templates/header', $vars, $return); $content .= $this->view($template_name, $vars, $return); $content .= $this->view('templates/footer', $vars, $return); if ($return) { return $content; } } }</code>
In the template() method:
After creating the custom loader class, update the constructor in your controllers to load the extended loader:
<code class="php">class My_Controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load = new MY_Loader(); } }</code>
Now, you can load your views with the template() method:
<code class="php">$this->load->template('body');</code>
This will load the header, body, and footer views automatically. You can also pass variables to the views as needed.
The above is the detailed content of How Can I Automate Header and Footer Inclusion in CodeIgniter Views?. For more information, please follow other related articles on the PHP Chinese website!