Returning Strings from Views with Code Igniter

When it comes to generating both static and dynamic web pages, CodeIgniter gives PHP developers the liberty of working with different approaches that can be easily adapted to suit the requirements of a huge variety of web applications. Building web pages using CI demands that you always deal with one or multiple views, generally represented in the form of HTML files that contain embedded PHP variables. Therefore, if you’re a CI user who want to learn to manipulate views in some clever ways, keep reading. In this series of articles, you’ll find a comprehensive guide to several methods you can implement within your own CI-based applications to handle view files in a truly efficient manner.

Introduction

Now that you know what to expect from this article series, it’s time to recapitulate briefly the topics that were discussed in the last installment. In that particular tutorial I demonstrated how to build a simple MySQL-driven application by using a combination of the “$this->load->vars()” method and nested views.

This approach allowed me to generate independently different sections of a front page, whose main area was populated with data fetched from a sample “users” MySQL table. Admittedly, including views within other views is a useful method that permits you to use certain parts of a web document across multiple pages of a web site; but the most interesting aspect of it is that it can be implemented in different ways.

Speaking more specifically, it’s possible to feed the “$this->load->view()” method of CI a third Boolean parameter, to return the contents of a view to calling code after the view has been parsed. This is a handy variation of the method demonstrated in the previous article, and in this tutorial I’ll be taking a close look at it, so you can grasp its underlying logic.

Now, it’s time to get things rolling on and see how to return strings from views with CodeIgniter. Let’s do it!

{mospagebreak title=Review: using nested views along with the load-vars() method}

It’s possible that you still haven’t had the chance to read the preceding article. As I mentioned, I went through the development of a simple MySQL-driven PHP application that utilized a mixture of nested views and the “$this->load->vars()” method to generate a dynamic web page. Below I included all of the source files that comprised this PHP program, so you can examine them in detail. 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

}

// generate web page with nested views and the ‘load->vars()’ method

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’);

}

}

?>



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


<?php

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

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

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

?>



(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>


Regardless of the apparently complex structure of the above CI-based application, each one of its parts performs some simple tasks. First, the controller is responsible for generating the typical sections of a web page, that is the header, contents area and footer. In this particular case, the main section of the web document is filled in with some database rows previously fetched from a MySQL table. But undoubtedly, the most relevant thing to spot here is how nested views are used to build the aforementioned web page sections.

Having reviewed quickly this approach to handling view files with CodeIgniter, the next thing that I’m going to discuss will be how to construct a web page similar to the above, but this time using an additional parameter with the “$this->load->view()” method. In case you’re not aware of it, when this method is called with a third argument, for instance like this:


$data[‘header’]=$this->load->view(‘myview’,array(‘title’=>’Header Section’),TRUE);


Then, not only the $title variable will be parsed within the view, but the resulting string will be returned to calling code, and in this case will be stored on the $data array as well. As you can see, this can be really useful for storing partial sections of a web page on variables, before rendering them completely on screen.

So, in the next section I’ll be explaining in more detail how to load views as shown before. However, to learn how this will be done, you’ll have to click on the link below and keep reading.

{mospagebreak title=Generating partial sections of a web page}

As I stated in the previous segment, it’s possible to pass a third Boolean argument to the $this->load->view()” method to return its output as a string after it has been parsed. By using this approach, it is also very simple to build sections of a web page independently, in a way similar to the method shown in the preceding article.

To demonstrate how this approach can be successfully implemented, first I’m going to create some new view files, which are listed below:


(definition of ‘main_page.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>

<style type="text/css">

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;

}

</style>

</head>

<body>

<div id="container">

<?php

echo $header.$content.$footer;

?>

</div>

</body>

</html>



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

<div id="header">

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

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p>

</div>



(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.</p>

</div>


Hopefully, at this point the group of view files coded above should be fairly familiar to you, right? Naturally, these are responsible for generating different sections of a web page, plus there’s one that acts like a general layout, called “main_page.php,” which loads the values returned from the other views.

With this handy view structure at our disposal, now it’s time to see how it can be used in conjunction with the strings returned by the “$this->load->view()” method to build an entire web document.

This task will be performed by a controller, and its definition will be shown in the next few lines. So, jump ahead and read the following section, please.

{mospagebreak title=Putting all of the views together}

In order to build a complete web page with the views that you saw in the previous section, it’s necessary to define a controller class that first stores the strings returned from each of them, and then passes this content to the layout view. If this sounds a bit confusing to you, the following web page controller should help to clarify any issues that you might have. Here it is:


<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// generate web page using partial sections

function index(){

// generate header section

$data['header']=$this->load->view(‘header_view’,array(‘header’=>’Header Section’),TRUE);

// generate content section

$data['content']=$this->load->view(‘content_view’,array(‘users’=>$this->db->get(‘users’)),TRUE);

// generate footer section

$data['footer']=$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’),TRUE);

// generate full web page

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

}

}

?>


Do you see how simple it is to generate a dynamic web page by returning strings with the “$this->load->view()” method? I guess you do. In the above example, each of the sections that make up the page are stored temporally on the $data array, and then it’s passed to the “main_page” view for displaying purposes.

Hopefully, this code sample should give you a clear idea of how to return contents from a view after they’ve been loaded, via the third “TRUE” argument as shown before.

And finally, assuming that all of this has been set up correctly, if you type the following URL into your browser:


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


Then you should get the following output:



Here you have it. At this point, you’ve learned how to use the “$this->load->view()” method in a slightly different way to generate a simple database-driven web application with CodeIgniter. All of the examples developed in this tutorial can be enhanced. For example, you might want to create a users model and utilize it within the controller to fetch database rows, instead of using the database class directly.

Whatever you decide to do, one thing is certain: CodeIgniter will keep you entertained for hours!

Final thoughts

In this fourth part of this series, I explained how to build a simple, yet dynamic, web page by returning strings from some views. As was illustrated earlier, this approach permits us to generate partial sections of a web document in a pretty intuitive and flexible fashion, and I’m sure that you’ll find even more useful ways to use it.

In the following article, I’ll be discussing how to make views even more "dumb" (if the term is actually applicable) by removing certain presentation logic from them. If you wish to learn how this will be done, don’t miss the upcoming tutorial!

Google+ Comments

Google+ Comments