Codeigniter comes with a nice way of dealing with views and such as part of its MVC structure.
However, it gets a bit more complicated when you want to replicate layouts, for instance if you have a header and footer, and don’t want to have to copy the code for this into lots of different views. After a couple of different views it gets pretty complicated and not very manageable.
So I’ve come up with a simple layouts/template system to work with Codeigniter in order to help alleviate some of the issues. You’re free to use this as you want.
Basically I’ve extended the controller class to include a couple more methods. Copy this into a file called MY_Controller.php in application/core/.
<?php class MY_Controller extends CI_Controller { private $content_areas; function __construct(){ parent::__construct(); } function add_view($content_area, $view, $data = array()){ $this->add_content($content_area, $this->load->view($view, $data, TRUE)); } function add_content($content_area, $content){ $this->content_areas[$content_area] = $content; } function render($layout = "default"){ $this->load->view('layouts/'.$layout, $this->content_areas); } } |
The idea is that you create “layouts”, and within these layouts you can define “content areas” and fill those content areas with either generated content, or with views you have created.
Go ahead and create a file called default.php in application/views/layouts/. It can look like this:
<html>
<head>
<!-- this is the first "content area" called "page_title" -->
<title><?=$page_title?></title>
</head>
<body>
<h1>My Website Layout</h1>
<div class="content">
<!-- this is the second content area, just called "main" -->
<?=$main?>
</div>
</body>
</html> |
And create a view called homepage.php in application/views/. It can look something like this:
Hello World. <button>Here is a button</button> |
Now you need to create a controller which extends MY_Controller:
class Homepage extends MY_Controller |
… and put this code in the index() function:
$data = array("text"=>"optional data variable if wanted for the views"); $this->add_view("main", "homepage", $data); // put the "homepage" view in the "main" content area, passing in the $data array if wanted $this->add_content("page_title", "Welcome to my website"); // pass in the standard text content $this->render(); // render the page with the layout and the content |
How you should be able to go to http://yourwebsite.com/index.php/homepage and see the layout, view and content rendered correctly.