How to Simplify Header and Footer Inclusion in CodeIgniter?

Susan Sarandon
Release: 2024-11-01 05:28:02
Original
730 people have browsed it

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>
Copy after login

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>
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!