Codeigniter: Best way to structure partial views

后端 未结 7 1944
無奈伤痛
無奈伤痛 2020-11-29 19:39

How would you structure the below page in Codeigniter?

\"alt

I thought about creating seperate c

7条回答
  •  情话喂你
    2020-11-29 20:02

    I can't vouch that this is the best approach, but I create a base controller like this:

    class MY_Controller extends CI_Controller {
    
        public $title = '';
        // The template will use this to include default.css by default
        public $styles = array('default');
    
        function _output($content)
        {
            // Load the base template with output content available as $content
            $data['content'] = &$content;
            $this->load->view('base', $data);
        }
    
    }
    

    The view called 'base' is a template (a view that includes other views):

    
    
        
            load->view('meta'); ?>
        
        
            
    load->view('header'); ?>
    load->view('footer'); ?>

    What this achieves is that every controller wraps its output in the base template, and that views have valid HTML instead of opening tags in one view and closing in another. If I'd like a specific controller to use a different or no template, I could just override the magic _output() method.

    An actual controller would look like this:

    class Home extends MY_Controller {
    
        // Override the title
        public $title = 'Home';
    
        function __construct()
        {
            // Append a stylesheet (home.css) to the defaults
            $this->styles[] = 'home';
        }
    
        function index()
        {
            // The output of this view will be wrapped in the base template
            $this->load->view('home');
        }
    }
    

    Then I could use its properties in my views like this (this is the 'meta' view that populates the element):

    echo "{$this->title}";
    foreach ($this->styles as $url)
        echo link_tag("styles/$url.css");
    

    I like my approach because it respects the DRY principle and the header, footer and other elements get included just once in the code.

提交回复
热议问题