Header and footer in CodeIgniter
Yes.
Create a file called template.php
in your views
folder.
The contents of template.php
:
$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');
Then from your controller you can do something like:
$d['v'] = 'body';
$this->load->view('template', $d);
This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:
Consider if you create a view called init.php
that contains the single line:
$this->load->view('html');
Now create the view html.php
with contents:
<!DOCTYPE html>
<html lang="en">
<? $this->load->view('head'); ?>
<? $this->load->view('body'); ?>
</html>
Now create a view head.php
with contents:
<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>
And a body.php
view with contents:
<body>
<div id="mainWrap">
<? $this->load->view('header'); ?>
<? //FINALLY LOAD THE VIEW!!! ?>
<? $this->load->view($v); ?>
<? $this->load->view('footer'); ?>
</div>
</body>
And create header.php
and footer.php
views as appropriate.
Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html>
and <body>
tags, your headers and footers will be loaded in.
$d['v'] = 'fooview'
$this->load->view('init', $d);
Here's what I do:
<?php
/**
* /application/core/MY_Loader.php
*
*/
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
For CI 3.x:
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
if($return):
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
return $content;
else:
$this->view('templates/header', $vars);
$this->view($template_name, $vars);
$this->view('templates/footer', $vars);
endif;
}
}
Then, in your controller, this is all you have to do:
<?php
$this->load->template('body');