Welcome Guest, Not a member yet? Register   Sign In
Basic Page Function
#8

I will create a simple `render` method in MY_Controller that allows for a very simple type of template system. It will auto-determine the the view to be used based on controller/method naming conventions. A simplified version looks a little like this:

Code:
protected function render($data=array(), $layout='')
{
  $dir = $this->router->fetch_directory();
  if (! empty($dir)) $dir .= '/';

  $view = $dir . $this->router->fetch_class() .'/'. $this->router->fetch_method();

  $data['view_content'] = $this->load->view($view, $data, TRUE);

  $layout = ! empty($layout) ? $layout : 'index';

  $this->load->view('theme/'. $layout, $data);
}

My current one is actually a bit more complex than that, and automatically formats and inserts status messages, gets stylesheet and script links to the view, etc.

Then, I have different layout files in the views/theme folder that contain the overall layout, or template, to use. The content of the primary view for that method is made available to the layout in the $view_content variable. A simple layout might be like this:

Code:
$this->load->view('theme/parts/header');
$this->load->view('theme/parts/navbar');

<div class="container">
    <?= $view_content; ?>
</div>

$this->load->view('theme/parts/footer');

You can create as many layouts as you need - for example, two-column layouts, or blog specific layouts, etc. But then using them in your controller is a single method call:

Code:
public function index()
{
    $this->render();
}

// or

public function index()
{
  $data = array();
  // Do stuff here that puts data in the $data array
  $this->render($data);
}

// or customize the layout use
public function index()
{
  $data = array();
  // Do stuff here that puts data in the $data array
  $this->render($data, 'two_col_left');
}
Reply


Messages In This Thread
Basic Page Function - by Tux - 10-22-2014, 12:48 AM
RE: Basic Page Function - by Rufnex - 10-22-2014, 01:27 AM
RE: Basic Page Function - by John_Betong - 10-22-2014, 06:16 AM
RE: Basic Page Function - by John_Betong - 10-22-2014, 06:20 AM
RE: Basic Page Function - by Rufnex - 10-22-2014, 09:45 AM
RE: Basic Page Function - by navotjer - 10-24-2014, 04:29 AM
RE: Basic Page Function - by jlp - 10-25-2014, 06:35 AM
RE: Basic Page Function - by puppy - 11-04-2014, 08:11 AM
RE: Basic Page Function - by kilishan - 10-25-2014, 08:02 AM



Theme © iAndrew 2016 - Forum software by © MyBB