Home  >  Article  >  Backend Development  >  How Can I Automate Header and Footer Inclusion in CodeIgniter?

How Can I Automate Header and Footer Inclusion in CodeIgniter?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 06:01:02798browse

How Can I Automate Header and Footer Inclusion in CodeIgniter?

Managing Headers and Footers in CodeIgniter: A Convenient Solution

The repetitive task of including headers and footers in every controller can be tedious. CodeIgniter provides a convenient way to automate this process.

One approach is to create a custom Loader class. In the MY_Loader.php file, add the following code:

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

This class extends the default CI_Loader class and adds a new method called template. The template method loads the specified template file and automatically includes the header and footer.

To use this custom loader, add the following line to the config/autoload.php file:

<code class="php">$autoload['libraries'] = array('MY_Loader');</code>

Now, in your controllers, you can use the template method instead of manually loading the header and footer:

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

This approach provides a convenient and reusable solution for managing headers and footers in CodeIgniter.

The above is the detailed content of How Can I Automate 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