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.
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!