How to Deal With Codeigniter Templates?
Unlike other frameworks CodeIgniter does not have a global template system. Each Controller controls it's own output independent of the system and views are FIFO unless otherwise specified.
For instance if we have a global header:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" ><html> <head> <title><?=$title?></title> <!-- Javascript --> <?=$javascript ?> <!-- Stylesheets --> <?=$css ?> </head> <body> <div id="header"> <!-- Logos, menus, etc... --> </div> <div id="content">
and a global footer:
</div> <div id="footer"> <!-- Copyright, sitemap, links, etc... --> </div> </body></html>
then our controller would have to look like
<?phpclass Welcome extends Controller { function index() { $data['title'] = 'My title'; // Javascript, CSS, etc... $this->load->view('header', $data); $data = array(); // Content view data $this->load->view('my_content_view', $data); $data = array(); // Copyright, sitemap, links, etc... $this->load->view('footer', $data); }}
There are other combinations, but better solutions exist through user libraries like:
See Comments Below
I've tried several ways to do codeigniter templates and the way that I stay is the fastest and simplest, is as follows.
In controller:
//Charge the view inside array $data['body'] = $this->load->view('pages/contact', '', true); //charge the view "contact" in the other view template $this->load->view('template', $data);
In view template.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es"> <head> <title>Template codeigniter</title> </head> <body> <div> <?=$body?> </div> <div class="clear"></div> <div>Footer</div> </div> </body> </html>
$body
is the view contact.
Make a library that includes all your views and send it data that you need to send to your content view. This is all!
<?phpclass Display_lib{ public function user_page($data,$name) { $CI =& get_instance (); $CI->load->view('preheader_view',$data); $CI->load->view('header_view'); $CI->load->view('top_navigation_view'); $CI->load->view($name.'_view',$data); $CI->load->view('leftblock_view',$data); $CI->load->view('rightblock_view',$data); $CI->load->view('footer_view'); }}