An Introduction to Views & Templating in CodeIgniter

An Introduction to Views & Templating in CodeIgniter

Tutorial Details
  • Program: PHP, CodeIgniter
  • Difficulty: Beginner
  • Estimated Completion Time: An hour

Views are a key ingredient in any MVC application, and CodeIgniter applications aren’t any different. Today, we’re going to learn what a view is, and discover how they can be used to create a templating solution for your CodeIgniter projects.

The first part of this tutorial will educate complete beginners to CodeIgniter on what a view is, and how to use them in a typical application. The second half will discuss the motivations for finding a templating solution, and guide the reader through the necessary steps for creating a simple, yet effective templating library. Interested? Let’s get started!


What is a View?

Views are special files used in CodeIgniter to store the markup outputted by the application, usually consisting of HTML and simple PHP tags.

“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 loaded from within controller methods, with the content inside the view subsequently displayed in the browser.


How to Load a view

To load (and display) a view in CodeIgniter, we use the built in Loader library.

$this->load->view('hello_world', $data, true/false);

This single line of code will tell CodeIgniter to look for hello_world.php in the application/views folder, and display the contents of the file in the browser.

Note that CodeIgniter allows you to exclude the .php suffix, saving a few keystrokes when typing the view’s filename you wish to load.

The second parameter, $data, is optional and takes an associative array or object. This array/object is used to pass data to the view file, so it can be used or referenced within the view.

The final optional parameter determines whether the view’s contents is displayed in the browser window, or returned as a string. This parameter defaults to false, displaying the content in the browser. We shall see later in the tutorial how this parameter can be used when creating a templating solution.


Creating & Displaying a View

To setup our first view, create a new file called hello_world.php in application/views and write the following simple HTML within:

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World!</title>
	</head>
	<body>
		<p>
			Hello world!
		</p>
	</body>
</html>

Now to display this view in the browser it must be loaded within a Controller method, using the aforementioned method.

So let’s create a new Controller file called hello_world.php in application/controllers and place the following code within. From within this controller, we shall load the newly created view.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Hello_world extends CI_Controller {
	
	public function index() 
	{
		$this->load->view('hello_world');
	}
}

Pointing your browser to http://your-ci-install.com/index.php/ will now result in the HTML in application/views/hello_world.php being outputted in the browser. You have successfully loaded a view!

Loading Multiple Views

Splitting a view into several files makes your website easier to maintain and reduces the likely hood of duplicate code.

Displaying a single View is all well and good, but you might want to split the output into several, distinct files, such as header, content & footer views.

Loading several views is achieved by merely calling the $this->load->view() method multiple times. CodeIgniter then concatenates the content of the views together before displaying in the browser.

Create a new file called header.php in application/views and cut & paste the first few lines from our original hello_world.php file in.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World!</title>
	</head>
	<body>

Similarly, create another file called footer.php in application/views and move the last two lines of hello_world.php in.

</body>
</html>

This leaves the hello_world.php view file just containing our page content.

<p>
	Hello world!
</p>

Now to display the page again, we have to load all three views (header.php, hello_world.php, footer.php), in order, within our controller.

Re-open application/controllers/hello_world.php and add the new $this->load->view() calls above and below the existing one.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Hello_world extends CI_Controller {
	
	public function index() 
	{
		$this->load->view('header');
		$this->load->view('hello_world');
		$this->load->view('footer');
	}
}

Because the header and footer views are now separate from the hello_world view, it means that they can be used in conjunction with any other views in the website. This means the code within the header & footer files don’t need to be copied over into any other views in the project that require this code.

Obviously this is a huge benefit as any changes to the HTML or content in the views, e.g adding a new stylesheet to the header, can be made to only one file, and not every file!


Using Data From the Controller in the View

Now, we’ll look at passing data from the controllers, so they can be used or outputted inside the view.

To achieve this, we shall pass an associative array, $data as the second parameter in the $this->load->view() call.

The values of this array will be accessible within the loaded view as variables, named by their respective keys.

$data = array(

	'title'		=>	'Hello World!',
	'content'	=>	'This is the content',
	'posts'		=>	array('Post 1', 'Post 2', 'Post 3')

);

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

The above code will give the variable $title the value ‘Hello World!’ inside the hello_world view.

How to Use Variables in Views

Once we have passed our data to the view files, the variables can be used in the usual way.

Typically, the view file will use the passed data to:

  • Display a variable’s value
  • Loop through arrays or object properties
  • Use conditional statements to show, or hide markup

I shall run through quick examples of how to do each.

To display a variable’s content use the simple and familiar, echo statement:

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

Looping through an array, or object, is a common task in view files, and can be achieved with a foreach loop:

<ul>
<?php foreach($posts as $post) { ?>
	
	<li><?php echo $post; ?></li>
	
<?php } ?>
</ul>

Simple conditional statements can be used in view files to slightly alter the output, depending on the data passed.

In general, you want to keep the use of conditional statements in views to a minimum, as overuse can lead to complicated view files, containing “business logic”. Splitting the view into different files, and deciding which is to be shown in the controller, is much more preferable.

<?php if ( $logged_in ) { ?>

	<p><?php echo 'Welcome '.$user_name; ?></p>
	
<?php } else { ?>

	<p>Please login</p>
	
<?php } ?>

The above example will either show a “Welcome” message, or a request for the user to login, depending on the value of $logged_in (true/false).


Templating in CodeIgniter

We’ve seen how splitting views into separate, smaller files can help organize and reduce the number of files in your CodeIgniter projects, but now multiple load view calls need to be made each instance a page is displayed.

Let’s assume that you have separate header and footer views, which are used to form a template. Every instance in the project where you wish to load and display a page using this template, three view loads have to be called. Not only can this clutter your controllers, but it results in a lot of repeated code – exactly the thing we wished to rid ourselves of by splitting the files up.

If you want to add extra markup to this template now, for example a sidebar menu. It could go in the header view, but it is more suited to be in its own separate view. Adding this new view to the existing template means going through each instance of the view loads, and adding another in. This can get messy fast.

We need a way to be able to embed view files that display individual page content, inside a template, without repeating code, and one that allows for modifications to be made to the template easily, and efficiently.

The following steps will guide you through creating a simple CodeIgniter library that fulfills these needs, as well as:

  • Enforcing a predictable and maintainable directory structure for your views
  • Allowing for multiple distinct templates to be used
  • Cutting down loading a page view to just one line of code

Once the library is written and in our CodeIgniter tool belt, we shall be able to display a templated page like so:

$this->template->load('template_name', 'body_view');

Much nicer!

Our templating solution will use view files which contain the full markup of a template, with a placeholder for another view file (with the page content) to be embedded within.

The placeholder will actually just be a variable named $body. When loading a templated view with our library, the content of the appropriate body view file will be assigned to this $body, embedding the view within the the template.


Step 1: Setting Up the Directory

We want to enforce a sensible, and predictable directory system for our view files to be housed in, so that our views are:

  • Easy to locate
  • Easy to determine which area of the application they belong to
  • Easy to maintain

Our directory system will also allow the library to cleverly determine where to look for view files, cutting down on the amount of code needed to load a templated view.

Create a new folder inside the application/views directory and name it templates. This folder will hold the different template views.


Step 2: Creating the Library

Libraries in CodeIgniter are just PHP classes and are loaded into Controllers much like views are.

$this->load->library('class_name');

Custom libraries you use in your CodeIgniter projects are stored in the application/libraries folder. To start writing our templating library, create a new file in this folder called Template.php, and place the following code in:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	class Template 
	{
		var $ci;
		
		function __construct() 
		{
			$this->ci =& get_instance();
		}
	}

The above code defines a new class, or library, named Template and the __construct() method within.

This method assigns the CodeIgniter super object to the $ci class variable , allowing all of CodeIgniter’s resources to be used by replacing $this with $this->ci in the usual method calls.

When the library is loaded in the CodeIgniter framework, the __construct() method is automatically called.

Writing the Load Method

Now we shall write the method to actually load a template view. We want to pass up to three parameters to this function:

  • The template name
  • The body view name (optional)
  • The data to be passed to the views (optional)

The result of this method being called, will be the template view being displayed in the browser, with the body view being embedded within, if one is supplied.

Underneath the __construct() method, place the following code:

function load($tpl_view, $body_view = null, $data = null) 
{
	if ( ! is_null( $body_view ) ) 
	{
		if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view ) ) 
		{
			$body_view_path = $tpl_view.'/'.$body_view;
		}
		else if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view.'.php' ) ) 
		{
			$body_view_path = $tpl_view.'/'.$body_view.'.php';
		}
		else if ( file_exists( APPPATH.'views/'.$body_view ) ) 
		{
			$body_view_path = $body_view;
		}
		else if ( file_exists( APPPATH.'views/'.$body_view.'.php' ) ) 
		{
			$body_view_path = $body_view.'.php';
		}
		else 
		{
			show_error('Unable to load the requested file: ' . $tpl_name.'/'.$view_name.'.php');
		}
		
		$body = $this->ci->load->view($body_view_path, $data, TRUE);
		
		if ( is_null($data) ) 
		{
			$data = array('body' => $body);
		}
		else if ( is_array($data) )
		{
			$data['body'] = $body;
		}
		else if ( is_object($data) )
		{
			$data->body = $body;
		}
	}
	
	$this->ci->load->view('templates/'.$tpl_view, $data);
}

The above code begins by checking if the $body_view parameter was supplied to the method. This variable will hold the name of the view to be used as the body in the template view.

	if ( ! is_null( $body_view ) )

If the parameter is supplied, a series of file_exists checks are made to try and locate the view file within our directory system.

if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view ) ) 
{
	$body_view_path = $tpl_view.'/'.$body_view;
}
else if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view.'.php' ) ) 
{
	$body_view_path = $tpl_view.'/'.$body_view.'.php';
}

The code first tries to locate the view file inside of a folder with the same name as the template in the application/views folder.

This is useful if sections of your project are drastically different from others, and use different templates. In these circumstances, it makes sense to group these view files together.

For example, a lot of websites display a different template for distinct sections, such as blogs. In our system, the blog view files can be placed inside the application/views/blog folder, seperating them from the main site views.

If the view file cannot be located in this folder, .php is appended to the end of the filename, and the check is made again. This is simply so .php can be excluded like the native $this->load->view() call.

If the file can still not be located, further checks for it’s location are made.

else if ( file_exists( APPPATH.'views/'.$body_view ) ) 
{
	$body_view_path = $body_view;
}
else if ( file_exists( APPPATH.'views/'.$body_view.'.php' ) ) 
{
	$body_view_path = $body_view.'.php';
}
else 
{
	show_error('Unable to load the requested file: ' . $tpl_name.'/'.$view_name.'.php');
}

This time, the code checks if the view file is located inside the application/views folder, and once again, if it cannot be found, appends .php and checks once more.

If the file is located in one of these places, the path is assigned to $body_view_path, otherwise an error message is thrown using the show_error() function built into CodeIgniter, and the script is terminated.

If the body view file was successfully located, the contents is assigned to the $body variable.

	$body = $this->ci->load->view($body_view_path, $data, TRUE);

We pass the $data parameter (null if not supplied) to the view load call, and set the third parameter to true to return the view’s output as a string.

We now add this $body variable to the list of data in $data so that it can be embedded in the template view when it is loaded.

if ( is_null($data) ) 
{
	$data = array('body' => $body);
}
else if ( is_array($data) )
{
	$data['body'] = $body;
}
else if ( is_object($data) )
{
	$data->body = $body;
}

If $data was not supplied to the load() call, $data is assigned to an array containing $body under key body. If the parameter was supplied, $body is added to the list by either assigning it to an array key, or object property, both also named body.

The $body variable can now be used in template view files as a placeholder for embedded views.

The last line of our method loads the template view file from the application/views/templates folder, and passes the $data variable in the second parameter.

	$this->ci->load->view('templates/'.$tpl_name, $data);

And that’s it! The library can now be put to use.


Using the Library

To start using our library, let’s create a template view, named 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 named content.php in application/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 the content view, within the default template.

$data = array(

	'title' => 'Title goes here',
	
);

$this->load->library('template');
$this->template->load('default', 'content', $data);

Note: the library has to be loaded in before you can call the 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.

If instead of a view file, you want a string to be embedded in the template, simply assign the string to the $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);

Quick Tip

I’ve found that grouping view files in folders by the controller, and even method, they belong to, really helps keep my views organized & easy to locate.

Organizing your views in this way results in the directory structure closely following the URL schema of controller/method.

For example, say your project has a controller named Members, containing method list.

An appropriate location for the list view file would be in application/views/members, or application/views/members/list, if this method loads multiple views.

This view could then be embedded into a template using our library with the following code:

$this->template->load('template_name', 'members/list');

Conclusion

The templating solution discussed in this tutorial is just one of a plethora of different ways to achieve templating in CodeIgniter.

You should hopefully now know what views are, and how to use them effectively – and efficiently – in your CodeIgniter projects.

The templating solution discussed in this tutorial is just one of a plethora of different ways to achieve templating in CodeIgniter. There are a number of different approaches, and I encourage you, reader, to research the other methods and determine which fits best for your projects.

If you have any comments or questions about the tutorial, or any insights on different templating solutions, please leave a comment below! Thanks for reading.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://roadha.us haliphax

    Good tip! I’d been doing something similar by adding header and footer view-loading functions into the body views, but this seems like a little bit more flexible.

  • Juan

    Stop promoting old framweworks, CI was great but the current version its preatty old. We want tips from the most advanced frameworks Laravel for example.

    • http://camdesigns.net CAM

      Way to troll man, I dig CI tuts+.
      put this in your pipe and smoke it : http://tutsplus.com/2012/06/sneak-peek-of-laravel-essentials/

      • Devin Dombrowski

        Agreed, Trolls be gone.

        CI may be older, but it is still very useful and powerful. It is one of the few frameworks that keeps things simple and to the point. CI3 is shaping up to fix and improve many issues as well.

    • http://community-auth.com brian temecula

      I started with Kohana, then went to CodeIgniter. Since then, I’ve tried Fuel, Laravel, Zend, and more. I keep going back to CI because it makes the most sense to me. Maybe it’s not 5.3+ php, but it still rocks. It’s easy to use, and that means better maintainability. Laravel does seem cool, but it’s ignorant to say CI is old. It is still in active development. I think the downside to CI is that it’s community seems more and more beginner web designers that don’t know any php, but for me, because I know php well, I find CI very awesome. It’s made me a lot of money!

  • http://developernetwork.info/ David D’hont

    @Juan, CodeIngiter has been covered a lot. But it is not dead nor is it bad.

    Take a look at this blog post from Phil Sturgeon’s Blogpost.

  • gemina

    yet another shitty for children :>

  • th3n3rd

    Well, even if CI is not based on PHP 5.3+ I don’t understand why developers(users of CI) still keep on use PHP4 classes, that’s old not CI!!! However Templating in a MVC framework is really simple as it is shown in this article because of the nature of mvc architecture, so I expected a more detailes and advanced article on this topic!

  • http://maomuffy.com Mfawa Alfred Onen

    Hey Guys,
    I respect nettuts because it has the great minds in the industry. Please the fact that most of you are professionals does not give you the leverage to look down on others, Codeigniter is still great for beginners and even advanced users. If you will prefer to use PHP 5.3+, then please use the appropriate framework, this article is also great and the author deserves some credits for his work here!

    • Jeff

      Well put Mfawa!

  • Satie

    CI works fine like Kohana, Zend, Laravel, etc.
    You can use it to complex projects. I’m using for e-commerce and configuration is easy, fast, fast, fast.

    It’s so stupid begin a war on framework, very very stupid.

  • http://developernetwork.info/ David D’hont

    1. This is not a promotion of an Old Framework. It’s a tutorial.
    2. This is free content, if you are not interested, move on.
    3. Everyone likes different things. That doesn’t give you the right to diss something that works for said person.

    And last but not least, CodeIgniter is Well Document, Tested, And has Hundreds of Hours worth of Man Hours put into the a free open source project. it’s a viable solution.

    So you have no right to call it old or bad. How about you get off your lazy ass, and start learning?

    Laravel has full documentation, if you want to get started with it, no one is stopping you.

    Quit being a bunch of ungrateful brats and be happy with what you have instead of demanding that these people do everything for you.

    • http://inkwell.dotink.org Matthew J. Sahagian

      Maybe it’s because I live in the United States and admittedly I’m not sure where you live, but, I’m quite certain most people in most places have the right to call CodeIgniter whatever they want. Calling it “old” is simply factual. Calling it bad is likely partially accurate, and if it wasn’t so old, I’d probably critique it myself and show why.

      You can disagree all you like with what someone says about it, but telling them they don’t have the right to say it? I’m not sure where this mentality comes from, but it’s rather odd to this Yankee.

      • http://developernetwork.info/ David D’hont

        What gives you the right to complain about something that you have done nothing to contribute to?
        Freedom of speech means you can. That doesn’t mean you should,

        This is a tutorial. If you are not interested in learning this; Then just leave it be. It can still be useful to other people. If you want to voice your opinion,

        Then put it on your blog, start a discussion on a forum, or send it in as an opinion piece to Envato. Feedback to Envato goes here!

      • http://inkwell.dotink.org Matthew J. Sahagian

        Yes, Freedom of speech means you can, hence, you have the right to do so. I don’t vote, but that, at least in the country I live in, does not restrict my right to criticize the president or elected officials, and in my opinion, it shouldn’t.

        I said nothing about what someone should or should not do. That being said, I’m more than willing to comment on what one should do.

        Firstly, I think it’s critical for developers of all experience levels to voice their opinions. I also think it’s critical that they do so in places where people “learn” as that is where their opinions will be most seriously debated and probably the most valuable to the community as a whole.

        Secondly, the assumption that such opinions are not valuable in any sense to the specific project being discussed is inaccurate. At the end of the day it will be up to the developers which part of the audience they wish to cater to, however, if, for example, the general opinion of the population was that code igniter being old and bad made it irrelevant or at the very least, approaching irrelevancy, that is something code igniter developers should certainly want to get a feel for.

        Finally, with all those things in mind, I don’t think the original author(s) approached it in the best way possible, but I certainly wouldn’t claim that they don’t have the right to do so. Furthermore, despite that there’s not a lot of meat to their comments, some of them are accurate. CodeIgniter is old and, as stated, before, it is (at least partially) bad (assuming bad means poorly designed). Ideally, they would justify at least the less obvious claim of the two so that people can understand why it’s bad and why there are better solutions.

      • David D’hont

        Let’s get a few things straight here.

        I don’t make assumptions. And the “rights” thing, was an Expression relating to Relevancy. Let it go.

      • http://vim.gentle.ro vimishor

        The beauty in an open source project is that the entire code base is at your disposal. If you dislike something, you can take the code and change things with your own hand.

        If you are hungry when you watch TV and complain that the refrigerator is too far from you, you will starve to death.

        Any open source software can be considered as a gift from developers. If you like the gift, use it ; if you don’t like it, move along and build something better. Complaining doesn’t get you gratitude from others.

      • Shariq Torres

        Matthew’s comments have nothing to do with the topic at hand are wholly irrelevant to the conversation. This post was not about which PHP framework is better. It was also not about the pros and cons of PHP 5.3+. It was about how to extend the native view capability of CodeIgniter.

        I don’t know what’s so hard about keeping your comments on topic. Hell, later on this thread Matthew gives us his fourth-grade level understanding of the 1st Amendment of the United States!!!! What the hell does that have to with PHP programming? I don’t care about your political views — most likely they are stupid, inconsistent, and involve denying other people their civil rights. But on the other hand, if you have another solution that the author of this post missed (in reference to extending CodeIgniter views), then I’m all ears.

      • Federico

        Matthew, nobody doubts that you in the United States can say whatever you like….(I never understood why you say your country is “America” when in fact you are just one of the many countries in the CONTINENT called America). So start not to criticize whatever “mentality” is not yours or not “yankee” as you said.

        You have the right to say whatever you want. That doesn´t mean you SHOULD say whatever you want.
        I think David D’Hont is right….maybe you´re taking very literally the word “right”…(we´re not talking about LAW here)…I think he made his point clear…It would be much more productive to actually write a tutorial than just complaining about FREE stuff. I think we all benefit from having a lot of tutorials here and with comments like those…it just inminently starts a debate that is far from the technical stuff we come here to look for.

        The author on this tutorial really must have dedicated time to write it…I also think he deserves some credit.

        If you read the different comments on different posts you ALWAYS find people complaining about “The new JS Framework..they say “who needs another new great js framework, write about the popular ones”…you also find people saying “CI?? what?? bring something new?!!”…Come on…I think David is pointing the same as me: Lets stop complaining and start commenting technically!

      • http://www.jeffrey-way.com Jeffrey Way

        Okay – let’s get off the “Don’t call yourself American” stuff. That insult comes up way too often. It’s been that way for hundreds of years, and I highly doubt that Canadians, Mexicans, or any of the other countries in the area are offended by it.

      • Gavin

        You’re an idiot. If you don’t like what you see, leave. And stop complaining.

    • http://inkwell.dotink.org Matthew J. Sahagian

      “are wholly irrelevant to the conversation.”

      My comments are relevant to another comment, hence why they are a reply to that comment. I made no original comment about CI or this particular article, I was simply calling out the ridiculousness of telling someone they don’t have a right to say something (particularly in this case since it was not even necessarily factually inaccurate). I mentioned in my response I didn’t agree with the original author(s) approach, doesn’t mean I can’t disagree with David D’hont as well.

      • Bratu Sebastian

        A couple of comments down, some people a bit upset, and he wins. I bet many of the people who read his comments went on his blog to see who he is. This is advertising. Talk about manipulation! :))

        CodeIgniter has bought me all the big projects and now, using cakephp at work, it’s still better than anything. Everybody has an opinion. We just don’t write our opinions on every wall.

      • Anon

        @Bratu, I didn’t check his blog to see who he is while reading his comments. Reading your post though made me do it. I guess I could say you are also advertising and you are even more manipulative than he is. Weird huh?

        Maybe I’m also advertising with my post and I might cause even more people now to check his blog. Even weirder…

        Anyway, I have no relation to this guy. I just wanted to tell you that your ‘advertising’ comment is actually working the other way around. I guess mine as well :)

  • RagingTaurus

    See what happens when you feed the trolls?…they throw in the bone and then move on to their next target. I don’t have any issue with anyone calling anything old or crap, as long as they give a reason. I just assume they are an asshat and not worth wasting my time if they don’t give a reason, simple really.

    Anyway, I’ve found Template Parser Class in CI to be pretty handy, lets me loop sections of pages with very little effort while keeping the code in the controller. Great when you want to allow the client to mess about with the HTML without breaking anything (to badly).

  • http://security4dev.com Jose

    I use HMVC with CodeIgniter, I love it:

    https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home

    “Modular Extensions – HMVC makes the CodeIgniter PHP framework modular. Modules are groups of independent components (typically, controller, model and view) arranged in one application sub-directory that can be dropped into other CodeIgniter applications.”

    With this module we can simulate views “like” symfony 1.4

    • http://www.pcbsd.pl piker3

      Yes, but only in CI1.x not in version CI 2.1

  • Roland

    If CI is not a framework for you then why did you even bother to post your nonsense? If you do not like it, ignore it.

    Is CI perfect? no, it is not.
    Is CI for everyone? no, it is not.

    however,

    CI has superb documentation
    CI has an active dev team (CI3 is shapping up to be pretty impressive)
    CI is easy to use, understand, and implement.
    CI is for new and advanced users
    CI’s community is active and helpful.
    CI is the Now backbone for ExpressionEngine (although, highly customized)

    I am currently using CI (and have been for a while now). Right now i am using it as the backbone for my own in-house CMS. Because of CI, and the CI community and their contributions i was able to get the basics of a CMS up and running within a day. A week later and after writing a few of my own classes (including my rolled template engine, Chat system, Blog, forum, Support Ticket System and custom admin) my CMS is almost there.

    This tutorial is a great starting point for those looking to use CI and want to have their own template system.

  • Me, myself and I

    :popcorn:

    Reading NetTuts comments is a lot better than watching Talk Shows; I will recommend this site to my aunt; she will for sure appreciate all your comments :)

    Please ladies, do not stop …

    :popcorn:

  • http://evanbyrne.com Evan

    CI’s template system really isn’t very good for working with layouts, and I wish they would overhaul it. Django is a good example of how a template system should be implemented in a web framework.

  • AnonymousPrime

    One of the first things I did when I started with CI is hook in the Smarty templating system. Between code blocks and template inheritance it made CI that much more powerful for me.

    Nothing wrong with getting one’s feet wet with CI’s built in views, but I would recommend the integration of Smarty, Twig or some other more robust templating engine to greatly increase productivity and reduce view complexity.

  • http://NA Anaon

    This is why comments should be disabled.

  • Gaurav Chandra

    Great Tutorial. But CI already has a parser. Won’t it be better to extend that?

    CI is one of the best php frameworks out there which is so light just like jquery. Have not used Laravel so cannot say anything much.

    The whole war of words here is not right. Tomorrow something better will come and then Laravel will get old.

    Just my 2 cents.

    • Curt

      Can you expand a little bit on how you would extend the parser? I do like this nettuts solution, but if you have a better one, please share!

  • Mohit Bumb

    Chod chadke apne salim ki gali anarkali disco chali

    are dekh ke tujhko dil main machi re khalbali anarkali disco chali

  • Linda Michelle

    Wow, insanely extensive and yet easily graspable! Kudos! I agree, Cl is one of the best frameworks, though comparing it to jquery? I have to take my side with Laravel, i think that’s here to stay. Or at least I hope so. Check out this site too, you’ll find so much handy info about webdev its uncanny: http://www.sitepoint.com

  • http://timeofcreation.com Time

    this information is very usefull, thank you

  • https://twitter.com/Matt_Asbury Matt

    Very interesting, although I use a slightly different way to avoid calling the multiple views in every method. I set up a parent controller and have all other controllers extend that one. In the parent controller I have a number of private properties, public setter methods for setting those properties, and a public display method which is the only one to use $this->load->view(); like this:

    /**
    * Used to create the page from the content provided
    *
    * @access public
    * @return void
    */
    public function _display()
    {
    // We only need to check that body data is available
    if (isset($this->body_data) && $this->body_data !== ”) {
    $this->load->view (‘pages/header’, $this->header_data);
    $this->load->view (‘pages/body’, $this->body_data);
    if (isset($this->current) && $this->current !== ”) {
    $this->load->view(‘pages/’ . $this->current, $this->body_data);
    }
    $this->load->view (‘pages/footer’, $this->footer_data);
    } else {
    show_404();
    }
    }

    All child classes then set the body of the content then use parent::_display(); when it’s ready to load the actual page.

  • Pawel

    Today I found a very interesting project for codeigniter – http://cibonfire.com/ – (Bonfire helps you build CodeIgniter-based PHP web applications even faster, by providing powerful tools and a beautiful interface you won’t be ashamed to show your client.)

    • Mat

      Thats seems to be very interesting, any other opinions??

  • http://www.cryode.com Eric Roberts

    “We’ve seen how splitting views into separate, smaller files can help organize and reduce the number of files in your CodeIgniter projects”

    Um, what? Was the editor asleep today? This article has quite a few small grammar errors, and overall is difficult to follow in certain areas because of terminology (or sometimes lack-there-of). I’m sure Sam tried hard and kudos to him for the effort and the relatively informative article, but editors need to step it up (need another one?).

    “We want to enforce a sensible, and predictable directory system for our view files to be housed in…”

    A third party library shouldn’t enforce ANYTHING if it doesn’t have to. It should be as flexible as possible for the developer, to allow for their own style. Give a developer what they need, not what you THINK they need. Let them alter it for their own specific needs if they want.

    Regarding the actual load() method, there are several things I could do to break it as it stands:

    - If no $body_view is supplied (leaving it NULL), the $body variable will never be added to $data, and thus never available to the template view (E_NOTICE error, no content).
    - If a $body_view is supplied, but $data is a string, the $body variable will again not be added, resulting in the same error above.
    - You could cut the number of file_exists() calls in half just by sanitizing the view names to have the appropriate extension (related: supplying $tpl_view with an extension will break ALL file_exists() calls).

    I personally don’t find this library efficient. First, it’s redundant – $this->load->view() checks all necessary file paths already (and throws an error if none are found). Second, it hardcodes the location of view files. What if the user chose to move them outside of the APPPATH? What if I want to add a Package path and pull views from that? What if I don’t want to use a /templates/ folder? But, it is an introduction to the possibilities of templates in CI, and (as mentioned) is just one of many ways to accomplish that.

    I also think that it would be more common for people to have a single template for their website. In which case, I would reorder the parameters to make the body view param first, and go down from there (potentially moving the template param to last, depending on any other functionality I might include). Then, going back to the “enforce a directory” comment earlier, the developer can choose whether or not to add a subdirectory for them or what have you.

    This article is a great introduction to CI views, and the possibilities available to developers for expanding upon them. Sam is certainly correct that this is just one of many many ways to create a template system (I’ve done things from creating a base controller, to extending the Loader class, to implementing full template systems such as Smarty). It’s just a nasty pet peeve of mine when tutorials have inefficient (or sometimes completely wrong) code.

  • http://guluzade.com jumancy

    There is an undefined variable($tpl_name) in the library

  • http://workshop200.com cmd

    Sorry, but original manual is practicly the same. No tricks…

  • ndriana

    Thanks for the example. Exactly what I was looking for. Time to optimize.

    Just a little remarque, the tutotial is dated July 2012. In PHP5, you’re recommended to use access modifier (private, protected or public) rather than var.

    var works but deprecated

  • http://roseavery.tumblr.com/ Richard Perez

    I don’t want to use a /templates/ folder But, it is an introduction to the possibilities of templates in CI, and is just one of many ways to accomplish that.It should be as flexible as possible for the developer, to allow for their own style.It is very useful to develpers..

  • Abhishekk

    i want to make a frame work in php

  • Zia khan

    this is very nice tutorials

  • Jamie

    On the first part when i try to load my first view all i get is the welcome page rather than the hello_world page. What am i doing wrong? i have created the hello_world controller and view.

  • Ondraft Studios

    It’s a really good tutorial, but handle template is a little bit more complicate. you could edit the load view method to manage templates and set up a default template an just wait require the name of a new template when it’s required. something like this:

    //normal i’ll load the default template added to the config file or someone called “default”

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

    //and when you require a new template:

    $this->load->view(‘home’, $data , [true/false], ‘template_name’);

    To work with this you onlye have to modify the view method at My_loader class(My_loader.php in core folder)
    adding this following lines:

    function view($view, $vars = array(), $return = FALSE, $layout = ‘default’)

    {

    // process requested view

    $return_value .= $this->_ci_load(array(‘_ci_view’ => $view, ‘_ci_vars’ => $this->_ci_object_to_array($vars), ‘_ci_return’ => TRUE));

    // process masterpage

    if ($layout)

    {
    $code_template = “templates/{$layout}.php”;

    $return_value = $this->_ci_load(array(‘_ci_view’ => $code_template, ‘_ci_vars’ => $this->_ci_object_to_array($vars), ‘_ci_return’ => TRUE));

    }

    if($return)

    return $return_value;

    echo $return_value;

    }

    }

  • Kevin S

    Hi Sam,

    Thanks a lot for the tutorials. I have go through all the five pages of tutorial. Here is my request: Can you create a tutorial on creating CDN library to use with Amazone CloudFront and S3?

    Kevin

  • http://www.facebook.com/mahendranayar Mahendran Nayar

    Will this load .css/.js without access forbidden error?

  • Jeffrey Davidson

    One of the questions I have about this great tutorial is what if we want to implement themes for our CI application to tie into the template library.

  • Code_joe

    Thanks for this, your tutorial was very useful to me.

  • http://www.facebook.com/rofi.basori Rofi Basori

    this is great tutorial