$this->load->view()

When you are using codeigniter, you will use function $this->load->view to load your ‘view’. In codeigniter user guide, a view is described as simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.

In my last project, some fragment on view is loaded in every page. They are header, footer and sidebar. And the content is dynamic. I don’t want to load views for every page. So i write a function in a library (or you can also extends the controller) to handle loading views for every page.

public function create_page($page = NULL ,$data = array()){
        $defaults = array('header' => array('title' => 'Home'),
            'content'=> '',
            'sidebar' => '',
            'footer'=> '');

        foreach ($defaults as $key => $val) {
                    $$key = ( ! isset($data[$key])) ? $val : $data[$key];
		}

        $this->ci->load->view('header',$header);
        if(! isset($page)){
            $this->ci->load->view('page',$content);
        }else{
            $this->ci->load->view('page/'.$page,$content);
        }
        $this->ci->load->view('sidebar',$sidebar);
        $this->ci->load->view('footer',$footer);
    }

In my function above, dynamic page is stored under ‘page’ folder. See the picture

Views

Views

Using this function is so simple,

$this->load->library('library_name');
$data = array(
                    'header' => array('title' => 'Testing Title'),
                    'content'=> array('data_content' => 'dummy content'));
$this->library_name->create_page('page_view',$data);

In the example above, i just send 2 variable to the view, $title for ‘header’ page and $data_content for ‘page_view’ page. In the ‘page_view’, i use the variables like this

echo $data_content;

any comments? CMIIW

1 thought on “$this->load->view()

  1. chipz

    lha ini yang saya mau ndan! saya tidak kepikiran kalo penggunaan library bisa cuman sebagai by-pass saja, pemberian content datane tetap di controller (kalo mau dari database bisa diambil dari model juga tentunya) nice post ndan!

    😀

    Reply

Leave a Reply to chipz Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.