roger
roger

Reputation: 33

Separate header and footer with MVC Codeigniter

I'm looking for a simple way to have the same header and footer displayed all the time whilst being able to switch out the main content area. I'm not sure how to achieve this with MVC.

Upvotes: 2

Views: 8384

Answers (4)

mos fetish
mos fetish

Reputation: 506

Similar to above, I do it like this:

$this->data['content']='your_content_view';
$this->load->vars($this->data);
$this->load->view('template');

Then in the template view:

$this->load->view('header');
$this->load->view($content);
$this->load->view('footer');

Views can load other views, so the template view loads a header view, then the view you specify in content, then the footer view.

Using this idea you can load sidebar views into the content, etc.

Upvotes: 0

Stephen Curran
Stephen Curran

Reputation: 7433

You could create a master view.

views/master.php

$this->load->view('header');
echo $content;
$this->load->view('footer');

And then create a base controller with a method to render the master view. The content of the subview is loaded and passed to the master view.

libraries/MY_Controller.php

class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function master_view($content_view, $data)
    {
        $data['content'] = $this->load->view($content_view, $data, true);
        $this->load->view('master', $data);
    }
}

Then extend this base controller and invoke the method of the base controller from your action methods.

controllers/items.php

class Items extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $data['items'] = $this->item_model->get_items();
        $this->master_view('items/index', $data);
    }
}

It tends to be more DRY than loading the header and footer in each view.

Upvotes: 11

canhnm
canhnm

Reputation: 61

Try Modular Seperation: http://codeigniter.com/forums/viewthread/121820/

Upvotes: 0

DampeS8N
DampeS8N

Reputation: 3621

Simply create a view for the header, and a view for the footer and spit them out at the top and bottom of each page. Or, create a template view and load it, then take other views and inject them into the content area of the template. Either way will get you where you want to be. If you want it to happen automatically, you can create the template view in the constructor of the controller and save it to a member of the controller class. Then use it such that say, $this->template will be the template view.

Upvotes: 1

Related Questions