Load header and footer view in CI

后端 未结 4 616
独厮守ぢ
独厮守ぢ 2021-01-06 23:29

Is there any way to load view \'header\'/\'footer\' without calling $this->load->view(\'header\') or $this->load->view(\'footer\') in e

4条回答
  •  猫巷女王i
    2021-01-07 00:23

    Here are a couple simple approaches to get you started:

    Create a template class:

    class Template {
    
        function load($view)
        {
            $CI = &get_instance();
            $CI->load->view('header');
            $CI->load->view($view);
            $CI->load->view('footer');
        }
    
    }
    

    Usage in controller:

    $this->template->load('my_view');
    

    Use a master view file:

    
    
      
    Your header
    load->view($view, $data); ?>
    Your footer

    In the controller:

    $this->load->view('master', array(
        'view' => 'my-view-file',
        'data' => $some_data
    ));
    

    I prefer the Template class approach, as it's easy to add methods to append templates areas, load javascript files, and whatever else you need. I also prefer to automatically select the view file based on the method being called. Something like this:

    if ( ! isset($view_file)) {
        $view_file = $CI->router->fetch_class().'/'.$CI->router->fetch_method();
    }
    

    This would load views/users/index.php if the controller is Users and the method is index.

提交回复
热议问题