How to handle menu template effectively in Codeigniter? How to handle menu template effectively in Codeigniter? codeigniter codeigniter

How to handle menu template effectively in Codeigniter?


There are 2 different things I would do to remedy this situation.

  1. I would wrap these 10 lines of code into a Model, because like you have said, it interacts with the database. Maybe create a Menu_model that has a get() function that returns the array of items you need loaded into your views. Then calling it in each controller would be as simple as

    $data['menu'] = $this->menu_model->get();  //assuming you autoload this model
  2. But lets not stop their as this is still a repeated line of code in EVERY controller function. Lets do this in the Controller's constructor so that these options are loaded globally in all views we produce.

assuming you're php5'd

function __construct() {    parent::__construct();    //get menu data    $global_data['menu'] = $this->menu_model->get();    //load into all views loaded by this controller    $this->load->vars($global_data);}

Then, your controller functions would look like this.

function show_pageA() {           $data['main_content'] = 'pageA';                    $this->load->view('template',$data);}

(Also, if this 'menu' logic spans multiple controllers, I would recommend rolling a custom MY_Controller.php that includes this logic so you again, are not repeating yourself in every controller constructor)


Rather than using Codeigniter views when it comes to templating and partials, you should look into using a templating library. There are quite a few around you might find useful and they all mostly handle breadcrumb navigation, view partials and other awesome things you're wanting to do.

I use Phil Sturgeon's template library in my Codeigniter projects because it's light and just works: http://philsturgeon.co.uk/code/codeigniter-template

Colin Williams template library is another popular templating library:http://williamsconcepts.com/ci/codeigniter/libraries/template/

And a few people seem to love using Ocular template library: https://github.com/lonnieezell/Ocular-Template-Library