2

在 Ci 上,您可以直接从控制器的构造函数加载视图,我正在加载页面的页眉和页脚(因为每个函数都相同)

class Add extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->view('header_view');
        $this->load->view('footer_view');       
    }

    function whatever()
    {
        //do stuff
    }

 }

但这会在加载我的函数之前加载页脚视图,那么有没有办法在每个函数末尾“手动”加载视图的情况下做到这一点?

4

3 回答 3

4

我会在主视图中添加页眉/页脚和数据,或者使用模板库(我使用这个

如果在功能的主视图中;

// in view for html page
<?php $this->load->view('header'); ?>
<h1>My Page</h1>
<?php $this->load->view('footer'); ?>
于 2012-06-12T14:12:14.483 回答
0

您不应该在构造函数中呈现任何视图。CI 控制器应该看起来更像这样:

class Add extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url'); 
    }

     function index()
     {
        $this->load->view('header_view');
        $this->load->view('home_page');
        $this->load->view('footer_view');
     }

     function whatever()
     {
        /*
         * Some logic stuff
         */

        $data_for_view = array(
            'product' => 'thing',
            'foo'     => 'bar'
        );

        $this->load->view('header_view');
        $this->load->view('show_other_stuff', $data_for_view);
        $this->load->view('footer_view');
     }

 }
于 2012-06-12T14:12:08.590 回答
0

我想出了这种方法:

 class Add extends CI_Controller{
    public function __construct()
    {
        parent::__construct();

        // load some static
        $this->data['page_footer'] = $this->common_model->get_footer();

    }
    private function view_loader () {
        //decide what to load based on local environment
        if(isset($_SESSION['user'])){
            $this->load->view('profile_view',  $this->data);
        } else {
             $this->load->view('unlogged_view',  $this->data);
        }
    }


    function index()
    {
        $this->data['page_content'] = $this->profile_model->do_stuff();

        // call once in every function. this is the only thing to repeat.
        $this->view_loader();
    }

  }
于 2014-02-19T00:47:33.807 回答