Praditha
Praditha

Reputation: 1172

Load header and footer view in CI

Is there any way to load view 'header'/'footer' without calling $this->load->view('header') or $this->load->view('footer') in every controller? Maybe a template that can be use in every view?

Upvotes: 2

Views: 2344

Answers (4)

No Results Found
No Results Found

Reputation: 102735

Here are a couple simple approaches to get you started:

Create a template class:

class Template {

    function load($view)
    {
        $CI = &get_instance();
        $CI->load->view('header');
        $CI->load->view($view);
        $CI->load->view('footer');
    }

}

Usage in controller:

$this->template->load('my_view');

Use a master view file:

<!-- views/master.php -->
<html>
  <header>Your header</header>
  <?php $this->load->view($view, $data); ?>
  <footer>Your footer</footer>
</html>

In the controller:

$this->load->view('master', array(
    'view' => 'my-view-file',
    'data' => $some_data
));

I prefer the Template class approach, as it's easy to add methods to append templates areas, load javascript files, and whatever else you need. I also prefer to automatically select the view file based on the method being called. Something like this:

if ( ! isset($view_file)) {
    $view_file = $CI->router->fetch_class().'/'.$CI->router->fetch_method();
}

This would load views/users/index.php if the controller is Users and the method is index.

Upvotes: 8

landons
landons

Reputation: 9547

I usually extend CI's Loader class to accomplish this...

<?php
class MY_Loader extends CI_Loader {

    public function view($view, $vars = array(), $return = FALSE, $include_header = TRUE, $include_footer = TRUE)
    {
        $content = '';

        if ($include_header)
        {
            $content .= parent::view('header', $vars, $return);
        }

        $content .= parent::view($view, $vars, $return);

        if ($include_footer)
        {
            $content .= parent::view('footer', $vars, $return);
        }

        return $content;
    }
}

Upvotes: 0

NeXuS
NeXuS

Reputation: 1797

Make a function that loads header and footer and places data in between.

Anyway the model on which CI is built requires the explicit loading of views (afaik).

Upvotes: 0

Alireza
Alireza

Reputation: 6848

You need to load view files somehow, this the way CI use to include the files.

Stick to the standard, I think it's the best practice.

Upvotes: 0

Related Questions