I'm using CodeIgniter and have a menu on the site that needs to read a list of cities from the database. This is simple to do if it's just on one or two pages - I load the model and call a function from the controller, and pass the data into the view.
But if I want it on every page, that means I have to keep copying the same code to every single controller function and pass the data into the view. (Note, I'm using a separate "header" view that contains the menu.)
What's the best way to automatically load some data on every page load and have it available to my view?
Create a new root controller class like MY_Controller
.
You can read how here: https://www.codeigniter.com/user_guide/general/core_classes.html
Then make all your controllers extend that class.
Add a function in MY_Controller
like this:
function show_view_with_menu($view_name, $data) {
$menu_data = $this->menu_model->get_menu(); // load your menu data from the db
$this->load->view('header', $menu_data); // display your header by giving it the menu
$this->load->view($view_name, $data); // the actual view you wanna load
$this->load->view('footer'); // footer, if you have one
}
Whenever you normally do load a view, instead do this:
$this->show_view_with_menu('view_for_this_controller', $data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With