I generate a menu from a database table using a function, and I’ve placed this in an extended base controller class:
<?php
class MY_Controller extends Controller {
public function __construct()
{
parent::Controller();
}
public function category_menu()
{
$this->load->model('category_model', 'category');
$categories = $this->category->get_categories();
$menu ="<ul class=\"menu_body\" id=\"nav_categories\">\n";
foreach($categories->result() as $row)
{
$menu .= "\t<li>" . anchor('listing/view' . $row->url, $row->name) . "</li>\n";
}
$menu .= "</ul>\n";
return $menu;
}
}
then naturally my controller looks like ~
<?php
class Site extends MY_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$data['menu'] = $this->category_menu();
$this->load->view('view', $data);
}
}
this does work, but it seems inefficient to have to do this for ~every~ page/view?
Or is this just a limitation of CI/MVC and there’s no other way of doing it.
thanks for any insight
The better way of doing this is rendering content in views. You can have partial templates, you don’t need to do string appending in the controller:
The TRUE in the call to view tell the function to return the rendered content and not put it into the buffer. You can then pass it to ‘view’. You can also get the categories and pass them into the view ‘view’ and load the partial template from there.