CodeIgniter User Guide Version 1.5.3


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.

Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page you should do so before continuing.

Using the example controller you created in the controller page, let's add a view to it.

Creating a View

Using your text editor, create a file called blogview.php, and put this in it:

Then save the file in your application/views/ folder.

Loading a View

To load a particular view file you will use the following function:


Where name is the name of your view file. Note: The .php file extension does not need to be specified unless you use something other then .php.

Now, open the controller file you made earlier called blog.php, and replace the echo statement with the view loading function:

If you visit the your site using the URL you did earlier you should see your new view. The URL was similar to this:

Storing Views within Sub-folders

Your view files can also be stored within sub-folders if you prefer that type of organization. When doing so you will need to include the folder name loading the view. Example:


Adding Dynamic Data to the View

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:

$data = array(
               'title' => 'My Title',
               'heading' => 'My Heading',
               'message' => 'My Message'

$this->load->view('blogview', $data);

And here's an example using an object:

$data = new Someclass();
$this->load->view('blogview', $data);

Note: If you use an object, the class variables will be turned into array elements.

Let's try it with your controller file. Open it add this code:

Now open your view file and change the text to variables that correspond to the array keys in your data:

Then load the page at the URL you've been using and you should see the variables replaced.

Note: You'll notice that in the example above we are using PHP's alternative syntax. If you are not familiar with it you can read about it here.

Creating Loops

The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows. For example, if you pull data from your database it will typically be in the form of a multi-dimensional array.

Here's a simple example. Add this to your controller:

Now open your view file and create a loop: