Using Nested Views with CodeIgniter

One of the most common tasks that a PHP programmer has to perform when developing web applications with CodeIgniter is loading a bunch of views to generate different sections of a web document. As with many other features provided by this framework, there are several ways to work with view files. This seven-part article series shows you many different ways to handle views. In this third part, we’ll focus on nested views and other methods.

Introduction

As I mentioned, there are several ways to work with view files with the CI framework, ranging from loading them sequentially and using the “$this->load()->vars()” method, to including views within other views.

Of course, it’s also possible to combine all of these approaches to build dynamic web pages, depending on the requirements of a specific PHP program. In this series of articles you’ll find concise code samples that will show you different methods that you can use for loading views within your CI-based applications.

And now that you’ve been introduced to the main subject of this series of tutorials, it’s time to refresh the topics that were discussed in the last one, in case you haven’t had opportunity to read it yet. In that article I explained how to improve the visual appearance of a basic web page, which was generated by loading sequentially three different views, where each of them was tasked with building the header, main area and footer section of the page.

Actually, CodeIgniter is smart enough to concatenate the contents of views, if they’re loaded in a sequential manner from inside a controller or from another view. This makes it much easier to generate web pages like the one mentioned above.

As I said before, however, there are several methods that can be utilized for loading view files, and in this third chapter of the series I’m going to discuss one that bases its functionality on the loader class that comes bundled with CI. If you’ve already seen the official user guide, then you may know that this class has a useful method called “$this->load->vars()” that behaves similarly to the “extract()” PHP native function.

By means of this method, it is very simple to replace in one single step all the variables included into multiple views with actual data. Therefore, in the next few lines I’m going to discuss how to use it to generate a dynamic web document, which will display some database contents.

Now, let’s get rid of the prologue and start discovering how to handle view data with CodeIgniter’s “$this->load->vars()” method. Let’s go!

{mospagebreak title=Review: loading views sequentially with CodeIgniter}

Before I proceed to demonstrate how to handle data in views via the “$this->load->vars()” method mentioned in the beginning, it would be useful to reintroduce an example developed in the preceding tutorial. As I mentioned, in that article I showed you how to build a basic web page by loading three distinct views sequentially.

Having said that, below I’ve listed the complete definitions of each source file that comprises the example in question. Here they are:


(definition of ‘webpage.php’ file – located at /application/controllers/ folder)


<?php

class WebPage extends Controller{

function WebPage(){

// load parent controller

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// load views sequentially

function index(){

// load ‘header’ view

$this->load->view(‘header_view’,array(‘header’=>’Header Section’));

// load ‘content’ view and pass database content

$this->load->view(‘content_view’,array(‘users’=>$this->db->get(‘users’)));

// load ‘footer’ view

$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’));

}

}

?>



(definition of ‘header_view.php’ file – located at /application/views/ folder)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Sample Web Page</title>

<link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" />

</head>

<body>

<div id="container">

<div id="header">

<h1><?php echo $header;?></h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>



(definition of ‘default.css’ file – located at /codeigniter/assets/css/ folder)


body{

padding: 0;

margin: 0;

background: #999;

}

#container{

width: 600px;

margin: 0 auto;

}

#header{

padding: 10px;

background: #eee;

}

#content{

padding: 10px;

background: #9cf;

}

#footer{

padding: 10px;

background: #eee;

}

h1{

font: bold 2em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

color: #039;

}

h2{

font: bold 1.5em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

p{

font: normal .8em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}



(definition of ‘content_view.php’ file – located at /application/views/ folder)


<div id="content">

<?php if($users->num_rows > 0):?>

<?php foreach($users->result() as $user):?>

<p><strong>First Name: </strong><?php echo $user->firstname;?></p>

<p><strong>Last Name: </strong><?php echo $user->lastname;?></p>

<p><strong>Email: </strong><?php echo $user->email;?></p>

<hr />

<?php endforeach;?>

<?php endif;?>

</div>



(definition of ‘footer_view.php’ file – located at /application/views/ folder)


<div id="footer">

<h2><?php echo $footer;?></h2>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>

</div>

</body>

</html>


In this particular case, the group of source files shown above are the building blocks of a simple CI-driven application that generates a dynamic web page by using three different views, which are loaded in a sequential way by a “WebPage” controller. Also, it’s clear to see how the controller fetches some rows from a “users” MySQL table, which are embedded into the “content_view.php” file for display purposes.

Moreover, it’s worthwhile to note here that the view responsible for building the header section of the web page also includes a separate style sheet called “default.css” for enhancing the visual appearance of the whole web document.

So far, so good. Having quickly reviewed the previous example, it’s time to see how to utilize the CI’s loader class to generate a web page similar to the one shown before. As you’ll see in a few moments, this process will require using some nested views along with the aforementioned “load->vars()” method. But to learn this topic in more detail, you’ll have to click on the link below and read the following section.

{mospagebreak title=Preparing a nested view for displaying database contents}

As I said in the introductory part of this series, another common approach that can be used for building different parts of a web page consists of using nested views. Sounds a bit complicated? It is not, trust me. Essentially, when using this method, there’s a main view that includes other views, which generate the distinct sections of a web document.

To clarify this concept a bit more, I’m going to code a new view file called “mainpage_view.php,” which will load three “partial views” sequentially. The file looks like this:


<?php

$this->load->view(‘header_view’);

$this->load->view(‘content_view’);

$this->load->view(‘footer_view’);

?>


As you can see, this main view simply includes other views to build the header, main area and footer section of the web page. Not too difficult to grasp, right? Naturally, based on this schema, it’s not necessary to change the definition of the “partial views,” so they remain the same, as indicated below:


(definition of ‘header_view.php’ file – located at /application/views/ folder)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Sample Web Page</title>

<link rel="stylesheet" type="text/css" href="../assets/css/default.css" media="screen" />

</head>

<body>

<div id="container">

<div id="header">

<h1><?php echo $header;?></h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>



(definition of ‘default.css’ file – located at /codeigniter/assets/css/ folder)


body{

padding: 0;

margin: 0;

background: #999;

}

#container{

width: 600px;

margin: 0 auto;

}

#header{

padding: 10px;

background: #eee;

}

#content{

padding: 10px;

background: #9cf;

}

#footer{

padding: 10px;

background: #eee;

}

h1{

font: bold 2em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

color: #039;

}

h2{

font: bold 1.5em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

p{

font: normal .8em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}



(definition of ‘content_view.php’ file – located at /application/views/ folder)


<div id="content">

<?php if($users->num_rows > 0):?>

<?php foreach($users->result() as $user):?>

<p><strong>First Name: </strong><?php echo $user->firstname;?></p>

<p><strong>Last Name: </strong><?php echo $user->lastname;?></p>

<p><strong>Email: </strong><?php echo $user->email;?></p>

<hr />

<?php endforeach;?>

<?php endif;?>

</div>



(definition of ‘footer_view.php’ file – located at /application/views/ folder)


<div id="footer">

<h2><?php echo $footer;?></h2>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>

</div>

</body>

</html>


Actually, including views within other views is a powerful technique that permits you to generate dynamic and static content with extreme ease. However, you should be aware of always keeping view files like  dumb structures that are only tasked with rendering data; no application logic should be delegated to them, since this is precisely the task of controllers.

Having now introduced the concept of nested views, the unique piece of this schema that still remains undefined is a controller that populates the variables included in the views with real data. Thus, in the following section I’m going to create this controller class, in this manner completing the development of this simple CI-based web application.

To see how the controller will be built, please follow the link and read the next few lines.

{mospagebreak title=Embedding actual data into views with a web page controller class}

In the previous section, you learned how to build a view file that also includes other partial views. However, it’s necessary to create a controller class that implements the logic required to generate a complete web page, which will be filled in with some database contents.

In this specific case, the controller that I’m going to define below will use the “$this->load->vars()” method included with CI’s loader class to replace the variables included within the views with actual data.

That being explained, the web page controller looks like this:


<?php

class WebPage extends Controller{

function WebPage(){

// load parent controller

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// generate web page with nested views

function index(){

// generate header, content and footer sections

$data=array(‘header’=>’Header Section’,’users’=>$this->db->get(‘users’),’footer’=>’Footer Section’);

// load variables in views

$this->load->vars($data);

// load ‘main_page’ view

$this->load->view(‘main_page’);

}

}

?>


Short to code and even simpler to read. Basically, all that the above “WebPage” controller does is  generate a simple web page whose main area has been populated with the contents of a “users” MySQL table. As I explained before, the replacement of variables included in the views is achieved with the $this->load->vars()” method, before loading the view that renders the main web document.

In summary, if all has gone well, if you type the URL below into your browser’s address field:


http://localhost/codeigniter/index.php/webpage


Then you should get the following output:



Hopefully with this simple example, you learned how to build a dynamic web page with CodeIgniter by using nested views along with the “$this->load->vars()” method. As usual with my articles on PHP web development, feel free to edit all of the code samples shown in this tutorial, so you can practice handling views with CodeIgniter.

Final thoughts

In this third installment of the series, I explained how to build a dynamic web page using a combination of CodeIgniter’s “$this->load->vars()” method and nested views. Hopefully you won’t have major trouble implementing this approach successfully when building your own PHP applications with CI.

In the next chapter, I’m going to extend the concept of nested views a bit further by using a third parameter within the “$this->load->view()” method shown before.

Now that you know what the upcoming article will be about, you can’t miss it!

[gp-comments width="770" linklove="off" ]

chat