Welcome Guest, Not a member yet? Register   Sign In
No need for templating libraries
#1

[eluser]Benjamin Midget[/eluser]
This is a walkthrough of how to do proper templating with CodeIgniter without using any extra libraries.

First, create your template:
Code:
<html>
<head>
  <title><?=$title?></title>
</head>
<body>
   <div class="header">
  Header Text here
</div>
   <div class="content">
      &lt;?=$content?&gt;
    </div>
  <div class="footer">
    Footer Text here
  </div>
&lt;/body&gt;
&lt;/html&gt;

Next, extend Controller:
Code:
class MY_Controller extends Controller{

protected $template = 'my/template/path';
protected $views = array();
protected $title = 'This is my site';

public function __construct()
{
   parent::Controller();
}

// you have to use this method now to load views as variables to the template.
protected function addview($path, $data, $name='content')
{
  $this->views[$name] = $this->load->view($path, $data, TRUE);
}

// this function does all the magic
public function _output($output)
{
  $data = $this->views;
  // this simply gives the template the proper title
  $data['title'] = $this->title;

  echo $this->load->view($this->template, $this->views, TRUE);
}


}

Finally, create your controller:
Code:
class Thispage extends Controller
{
public function __construct()
{
  parent::__construct();
  $this->title = 'This is the Thispage section of the site';
}

public function index()
{
   $data = array(); // get data from a model here
   $this->addview('thisview', $data);
}
}

That's it. You if you have multiple parts to the template, simply use something like:

Code:
$this->addview('some/view', $data, 'leftcolumn');
$this->addview('another/view', $data, 'rightcolumn');

I've also done this another layer deep by having multiple templates, but in order to do that you have to run an include at the top of your controller class.

If anyone wants to know how to do that, let me know.
#2

[eluser]Colin Williams[/eluser]
Not sure I get the point entirely. This works if you ALWAYS want to use such a templating setup. By using _output() and doing nothing with the supplied argument, you are forced into using this system (not to mention bypassing caching). Kinda sucks if, say, I want to output something simple like JSON or simple strings. Granted, I still could, but it becomes a bit of a hack to do something as simple as printing a string. Using a template class lets you opt-in.


And it's false to say that your aren't using a templating library. You've just merged a very simple and rigid one into the Controller class.

The appropriate use of _output() is not to generate new output, but to run any necessary processes or manipulate what should be output.
#3

[eluser]Benjamin Midget[/eluser]
@Colin: well spoken and good point.
#4

[eluser]Colin Williams[/eluser]
Well, I've been down that road before.




Theme © iAndrew 2016 - Forum software by © MyBB