Creating a database-generated menu on every page in CodeIgniter?
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, a开发者_开发技巧nd 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);
You define your own Application_Controller
, which extends CI_Controller
. All of your own controllers then extend your Application_Controller
rather than the CI_Controller
.
In the __construct()
of your Application_Controller
you'll introduce the code you've been copying and pasting everywhere previously.
My solution was just to create a display class that handles these things. A simplified version:
class Display
{
public function load_pages($name, $data = array()) {
$CI =& get_instance();
// Top and header templates
$CI->load->view('header.php', $data);
// Default to loading the one template file
$CI->load->view($name, $data);
// Footer template
$CI->load->view('footer.php');
}
}
I have it doing fancier stuff, such as setting default values (page title, meta tags) and loading js/css, etc. It works just like a shortcut to having to copy/paste the regular templates that I load but also allows me to define a custom template setup if I need to, unlike if you have it do so automatically be extending your controller class.
I haven't had the need to but you can also specify different functions within this class to load different sections of the site, such as load_admin_pages()
or some such. In my case I handle that just by setting a prefix parameter that gets prepended to the file paths and that's gotten what I need for my current project.
精彩评论