The view

A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.

Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page you should do so before continuing.

Adding Dynamic Data to the View

Data is passed from the controller to the view by way of an array (or an object) in the second parameter of the view loading function. Here is an example using an array:

$data = array(
               'title' => 'My Title',
               'heading' => 'My Heading',
               'message' => 'My Message'
          );

$this->load->view('blogview', $data);

Let's try it with your controller file. Open it add this code:

<?php
class Blog extends CI_Controller {

    function index()
    {
        $data['title'] = "My Real Title";
        $data['heading'] = "My Real Heading";

        $this->load->view('blogview', $data);
    }
}
?>

Now open your view file and change the text to variables that correspond to the array keys in your data:

<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
    <h1><?php echo $heading;?></h1>
</body>
</html>

For more, visit the original documentation page.

Post A Comment

Anti-Spam Quiz: