Code Igniter Library for Layouts

October 28th 2009

Here is a simple library that takes advantages of layouts in code igniter. You can call it in your controller like:

$this->layout->view('dashboard');

You can pass data to it just like load->view:

$data = array('foo'=>'bar'); $this->layout->view('dashboard',$data); 

Either configure your autoloader to load the layout or load the library in your controller:

$this->load->library('layout');

If you wish to change the layout from default you do so in your controller:

$this->layout->setLayout('secondary');

<?php  
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout {

	var $obj;
	var $layout;

	function Layout($layout = "default"){
		$this->obj =& get_instance();
		$this->layout = $layout;
	}

	function setLayout($layout){
		$this->layout = $layout;
	}

	function view($view, $data=null, $return=false){
		$loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);
		if($return):
			$output = $this->obj->load->view('layouts/'.$this->layout, $loadedData, true);
			return $output;
		else:
			$this->obj->load->view('layouts/'.$this->layout, $loadedData, false);
		endif;
	}
	
}
?>
352 downloads

2 COMMENTS

Jeffery says...
this is very helpful. thanks but how would I create a function to disable layouts within a view i.e. for ajax requests
i created a function in the library called disableLayout to be called in my view
$this->layout->disableLayout();
but i havent found anything that works
Jeffery says...
figured out a simple way

on functions that i intend to use for ajax i just use the loader

$this->load->view instead of $this->layout->view

ADD YOUR COMMENT

(optional)
(optional)
Use (Gravatar) for your avatars.