我正在尝试确定从 Controller 中的同一方法调用多个 View 的最佳实践。
是在 Controller 中进行一个 View 调用,然后让该 View 调用它需要的所有 View ,还是在 Controller 中按顺序调用所有需要的 View ?
示例:
function index(){
//set all data variables
//then send them to the view
$this->load->view($index_view, $data);
}
或
function index(){
//set variables
//then call each view
$this->load->view($header_view, $header_data);
$this->load->view($body_view, $body_data);
$this->load->view($footer_view, $footer_data);
Codeigniter 指南显示了两种方法,但似乎没有建议最佳实践...有吗?
最佳答案
我不喜欢在 View 中包含页眉/页脚的方式,也不喜欢在每个 Controller 函数中每次都加载页脚和页眉。
为了解决这个问题,我用自己的 View 显示功能扩展了 Controller 类。
<?php
// in application/libraries/MY_Controller.php
class MY_Controller extends Controller {
function _displayPage($page, $data = array()) {
$this->view->load('header', $data);
$this->view->load($page, $data);
$this->view->load('footer', $data);
}
}
?>
// in application/controllers/home.php
<?php
class Home extends MY_Controller {
function index() {
$this->_displayPage('home/index', array('title' => 'Home'));
}
}
?>
不确定这是否是 CodeIgniter 的“最佳实践”,但对我来说很有意义。
关于model-view-controller - 在 Codeigniter 中显示多个 View 的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1217275/