(created: January 21, 2015; last update: -)
In the previous tutorial we worked a bit with the controllers. Now, remember how I told you that when talking about MVC patterns, the controllers send the data to the views so that the data would be outputted to the browser?
Well, now we will talk a bit about these views. In particular, we will talk about the view that is called by the Welcome controller, “welcome_message“.
The views can be found in application/views directory, so we will find the welcome_message.php in there.
We will see a plain page if we look inside it… so, let’s delete everything and just create a basic html structure:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Your Website</title> </head> <body> <h1>Hello from your CodeIgniter application</h1> <p>Hello</p> </body> </html>
Now, if in the controller we’ve defined some variables (and we did), how would we go about using them in the view? As I already mentioned in the previous tutorial, when loaded from the controller, the view can receive variables inside an array:
Inside the view, the variables can be accessed by calling the keys of the array as variables. So, if for example we have an array like this one:
$data = array('page_title'=>'This is the title of the page', 'another_var' => 6);
…when we will be inside the view we can access those keys by simply translating them into variables:
echo $page_title; echo $another_var;
Let’s put what we’ve learned into practice. As you remember, in the controller we’ve defined a page title ($data[‘page_title’] = ‘Our first CodeIgniter application’; ). Now in the view we simply replace the hard-coded page title with the variables sent by the controller:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $page_title;?></title> </head> <body> <h1>Hello from <?php echo strtolower($page_title);?></h1> <p>Hello</p> </body> </html>