Multiple views and templates with Code Igniter: Method 1
Why am I writing this?
Over the past couple weeks, I've been asked several times what I feel the best method is for managing a template-like system in CodeIgniter. Instead of continually explaining the various different methods each and every time, I eventually started using a copy of a long IRC discussion on the subject to introduce users to the concept.
Well, I still don't think it gets the point across, so we'll dive into it with this multi-part series.
The basics:
First, let's explain some basics: CodeIgniter (CI) is an MVC PHP framework. It is derived from ExpressionEngine and is quite flexible. Not as strict an implementation of MVC as something like CakePHP would be, CI still follows a set of defaults, and understanding the concepts behind these defaults is key.
Let's take a peek at the CI User Guide for a moment. When you render a view from your controller, what you are doing, essentially, is passing program control from the controller to the view. In the MVC model, this means moving into the presentation and interaction part of the model.
So, in your controller, you would have:
$this->load->view('yourView');
And you will have a view named "yourView.php"
Now, how about those time-saving templates?
This is the method to call the view. Now, lets say that you want all your views to have some shared elements. For example, on this site, the header, sidebar, and footer are the same on ever page. It would be silly to actually put that code in every view.
What if you got the site all done, and had 20 different view files. And suppose you realized that one of the links you added to your sidebar was wrong. Yeah, now you see the point of separating your shared code.
So, in your view, instead of all that header stuff, create a file called "header.php" and place all of your header code in there.
After calling the "yourView.php" file, instead of all that header code, you would place this at the top of the view:
$this->load->view('header');
This essentially performs an include, but does not pass program control to that view.
In the view you would essentially have this for a pretty standard site:
$this->load->view('header');
$this->load->view('navigation');
...put the content unique to this view here...
$this->load->view('sidebar');
$this->load->view('footer');
So, this is the basic way to manage a pseudo-templating system with CI. In the next example in the series, I'll show you how to start adding some decision making for the occasion that you may have views that wont have a sidebar or a footer.
Next entry: ExpressionEngine Users: RSS Patch required
RSS 2.0