Load header and footer view in CI

后端 未结 4 574
独厮守ぢ
独厮守ぢ 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条回答
  • 2021-01-07 00:16

    You need to load view files somehow, this the way CI use to include the files.

    Stick to the standard, I think it's the best practice.

    0 讨论(0)
  • 2021-01-07 00:21

    Make a function that loads header and footer and places data in between.

    Anyway the model on which CI is built requires the explicit loading of views (afaik).

    0 讨论(0)
  • 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:

    <!-- views/master.php -->
    <html>
      <header>Your header</header>
      <?php $this->load->view($view, $data); ?>
      <footer>Your footer</footer>
    </html>
    

    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.

    0 讨论(0)
  • 2021-01-07 00:26

    I usually extend CI's Loader class to accomplish this...

    <?php
    class MY_Loader extends CI_Loader {
    
        public function view($view, $vars = array(), $return = FALSE, $include_header = TRUE, $include_footer = TRUE)
        {
            $content = '';
    
            if ($include_header)
            {
                $content .= parent::view('header', $vars, $return);
            }
    
            $content .= parent::view($view, $vars, $return);
    
            if ($include_footer)
            {
                $content .= parent::view('footer', $vars, $return);
            }
    
            return $content;
        }
    }
    
    0 讨论(0)
提交回复
热议问题