Amitav Roy

Blog on web and travel

Part 3 Sending data from controller to views and partials

Posted on 17 Feb 2013 by Amitav Roy

Part 3 Sending data from controller to views and partials

In this tutorial, I will show how we can send data from the controller to the view and then into the partials which will then react to the data and do their work. The controller will decide which JS files to load in the footer template and also send the page title in the header template.

In the last two tutorials, I have shown how we set up the framework environment, enable clean URL editing the configuration file and also adding the .htaccess file. Then in the next tutorial, I showed how we can use partial views to create one page and created the starter page which is featured on the bootstrap website.

Now in this tutorial, we will start sending useful data within the views and start rendering meaningful information. I have added a for each loop in my footer view so that it will load all the scripts which I decide to load for that particular page inside my controller. This is a very simple way of passing data from the controller to the view and subsequently into another child view (or partial view).

In this, I have only shown you the index function from the home controller. I created an array $data and it has two more array inside it – the header and the footer. The header array has title inside it and the footer has another set of array which has the js file name and folder. I have added the filename as key and folder name as value because if we have multiple files inside one folder to load and the key is the folder name and not filename (which will be unique) only the last file will be loaded. Yes, there are other ways, but for now this works well.

Inside the header and the footer view I have a for each loop which checks if the data is present and reacts accordingly. And that data is being passed by the main page_view layout php file.

And here is the partial view for header:

And here is the partial view for footer:

I have created the homescript javascript file and also added a console.log to verify if the file is coming on to the page or not. Here is the thing, I want jQuery on every page hence it is directly appended. Where as the homescript.js file is something which will be unique to home page or I can also have a few generic script files which I will load on multiple pages but not all.

You can find the full code base on Git hub… Click here