In the previous section, you learned how to build a view file that also includes other partial views. However, it’s necessary to create a controller class that implements the logic required to generate a complete web page, which will be filled in with some database contents. In this specific case, the controller that I’m going to define below will use the “$this->load->vars()” method included with CI’s loader class to replace the variables included within the views with actual data. That being explained, the web page controller looks like this: <?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 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'); } } ?> Short to code and even simpler to read. Basically, all that the above “WebPage” controller does is generate a simple web page whose main area has been populated with the contents of a “users” MySQL table. As I explained before, the replacement of variables included in the views is achieved with the $this->load->vars()” method, before loading the view that renders the main web document. In summary, if all has gone well, if you type the URL below into your browser’s address field: http://localhost/codeigniter/index.php/webpage Then you should get the following output:
Hopefully with this simple example, you learned how to build a dynamic web page with CodeIgniter by using nested views along with the “$this->load->vars()” method. As usual with my articles on PHP web development, feel free to edit all of the code samples shown in this tutorial, so you can practice handling views with CodeIgniter. Final thoughts In this third installment of the series, I explained how to build a dynamic web page using a combination of CodeIgniter’s “$this->load->vars()” method and nested views. Hopefully you won’t have major trouble implementing this approach successfully when building your own PHP applications with CI. In the next chapter, I’m going to extend the concept of nested views a bit further by using a third parameter within the “$this->load->view()” method shown before. Now that you know what the upcoming article will be about, you can’t miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|