Home > Article > Backend Development > How to Automate Header and Footer Inclusion in CodeIgniter?
Incorporating Headers and Footers Seamlessly in CodeIgniter
The need to repeatedly load header and footer views in every controller can be tedious. To address this, let's explore a solution that automates this process and provides flexibility in customizing these common elements.
In CodeIgniter, a custom loader class can be created to achieve this. By overriding the template() method in MY_Loader.php, we can define a function that combines the header, body, and footer views.
<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>
For CodeIgniter 3.x, the modified template() method would include an additional elseif statement:
<code class="php">// application/core/MY_Loader.php class MY_Loader extends CI_Loader { public function template($template_name, $vars = array(), $return = FALSE) { if($return): $content = $this->view('templates/header', $vars, $return); $content .= $this->view($template_name, $vars, $return); $content .= $this->view('templates/footer', $vars, $return); return $content; elseif: $this->view('templates/header', $vars); $this->view($template_name, $vars); $this->view('templates/footer', $vars); endif; } }</code>
With this custom loader, controllers can simply load the desired body content without worrying about header and footer views:
<code class="php">// controller $this->load->template('body');</code>
This approach provides flexibility, allowing for easy customization of header and footer content without cluttering the controllers.
The above is the detailed content of How to Automate Header and Footer Inclusion in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!