Skip to content

Adding Layouts c.q. data format to CI

World Wide Web Server edited this page Jul 4, 2012 · 12 revisions

Category:Plugin::Data_Presentation This is a work in progress, so be gentle: @todo: Add detection of missing layout for a certain view and an (error) message accordingly. @todo: add examples

In this article I'll explain why layouts are an essential tool in developing large applications.

Who hasn't stumbled upon the fact that often you are presenting the very same data but in a different format?

Consider blog posts. Often you represent an overview of say the latest x posts in an xhtml format for the convenience of the user. Complete with an navigational structure and markup. However, now you want to add an RSS feed for these latest x posts to your site. Essentially this is the same data. Why whould you want to write a lot of code to simply represent the same data, but just in an other format? Right, you wouldn't.

So that's where layouts or (data format views :P) step in.

By adding these functions and property to your own BaseController (or to the CI Controller, or whatever you inherit your controllers from) you'll enable layout support. [code] class MY_Controller extends Controller { protected $layout = 'xhtml';

/**

  • This function remaps the url and retrieves the desired extension from it. It then calls the appropiate controller method.
  • @param string $aMethod */ function _remap($aMethod) { $lParams = $this->uri->segment_array(); array_shift($lParams);array_shift($lParams);
$lMethod = $aMethod; 
if (strpos($lMethod, '.') !== False) 
  list($lMethod, $this->layout) = explode('.', $lMethod);
  
$lMethod = (empty($lMethod) ? 'index' : $lMethod);

# Let's be sure that we only call a public method
if (method_exists($this, $lMethod) && !method_exists(__CLASS__, $lMethod)) {
  call_user_func_array(array($this, $lMethod), $lParams);
} 
else {
  show_404($lMethod);
}

}

/**

  • This function provides a shortcut to the load->view function. It also appends the current layout so you won't get lost.
  • @param string $aView */ protected final function view($aView, $aData=array()) { $this->load->view($this->layout.DIRECTORY_SEPARATOR.$aView, $aData); } } [/code]

This means you should arrange your views folder like: /views/layout/... As the $this reference in your views is the CI_Loader and not the Controller you won't have access to the modified view function. This has an advantage and a disadvantage: You have to specify the layout everytime you load a view / partial in your views causing overhead and things to maintain. This holds the advantage that you have extra control over which function should be loaded.

Discussion: [url=http://codeigniter.com/forums/viewthread/87380/]http://codeigniter.com/forums/viewthread/87380/[/url]

Clone this wiki locally