在CodeIgniter的每一页上创建一个数据库生成的菜单? [英] Creating a database-generated menu on every page in CodeIgniter?

查看:108
本文介绍了在CodeIgniter的每一页上创建一个数据库生成的菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CodeIgniter,并在网站上有一个菜单,需要从数据库中读取城市列表。这是很简单的做,如果它只是在一个或两个页面 - 我加载模型并从控制器调用一个函数,并将数据传递到视图。



但是如果我想在每一个页面,这意味着我必须保持相同的代码复制到每个单一的控制器函数,并将数据传递到视图。 (注意,我使用一个单独的头视图包含菜单。)



在每个网页加载时自动加载一些数据的最好方法是

创建一个新的根控制器类 MY_Controller



您可以在这里阅读: https://ellislab.com/codeigniter/user-guide/general/core_classes.html



然后让所有控制器扩展该类。



MY_Controller 中添加一个函数,如下所示:

  function show_view_with_menu($ view_name,$ data){
$ menu_data = $ this-> menu_model-> get_menu //从db
$ this-> load-> view('header',$ menu_data)加载菜单数据; //通过给菜单显示标题
$ this-> load-> view($ view_name,$ data); //您要加载的实际视图
$ this-> load-> view('footer'); // footer,如果你有一个
}

而是这样做:

  $ this-> show_view_with_menu('view_for_this_controller',$ data); 


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://ellislab.com/codeigniter/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);

这篇关于在CodeIgniter的每一页上创建一个数据库生成的菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆