Home  >  Article  >  Backend Development  >  How to Simplify Header and Footer Inclusion in CodeIgniter?

How to Simplify Header and Footer Inclusion in CodeIgniter?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 05:28:02731browse

How to Simplify Header and Footer Inclusion in CodeIgniter?

Simplifying Header and Footer Inclusion in CodeIgniter

Programmers often find it tedious to manually load header and footer views in every controller. This becomes even more problematic when changes need to be made to these common elements across the application. Here's a solution that automates this process:

In CodeIgniter's core/MY_Loader.php file, create an extension of the CI_Loader class:

<code class="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>

Alternatively, for CodeIgniter 3.x, the following code can be used:

<code class="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;
    else:
        $this->view('templates/header', $vars);
        $this->view($template_name, $vars);
        $this->view('templates/footer', $vars);
    endif;
    }
}</code>

In your controller, you can now use the template() function like this:

<code class="php">$this->load->template('body');</code>

This method automates the inclusion of the header and footer views, making it much easier to update and maintain your application's layout.

The above is the detailed content of How to Simplify Header and Footer Inclusion in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn