
“A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.”
The first part of this tutorial will educate complete beginners to create a template view, named
default.php
Interested? Let’s get started!
default.php
in application/views/templates
, and place the following HTML/PHP inside:<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1>Default template</h1>
<div class=”wrapper”>
<?php echo $body; ?>
</div>
</body>
</html>
In this template, we reference two variables,$title
and$body
.
Recall that in our template files,$body
serves as a placeholder for an embedded view.
We shall now make another view to be embedded inside this template. Create a new file namedcontent.php
inapplication/views/
and place this simple HTML inside:
<p>
Hello world!
</p>
We are now ready to load the templated page view from within a controller.
Inside any controller method, place the following code to display thecontent
view, within thedefault
template.
$data = array(
‘title’ => ‘Title goes here’,
);
$this->load->library(‘template’);
$this->template->load(‘default’, ‘content’, $data);
load
method. To save yourself loading the library every time a template view needs to be displayed,autoload the class by adding it to the array of libraries in
application/config/autoload. php
.$data
array using the key body
, and pass null
as the second parameter in the load call.$data = array(
'title' => 'Title goes here',
'body' => 'The string to be embedded here!'
);
$this->template->load('default', null, $data);