Menu

How to create and load view in codigniter?

  • In codigniter, views will never call directly. They must be loaded by the controller. In an MVC framework, the controller is responsible for loading a particular view.
  • Before going to view section, you must read about controllers in codigniter.

Page Contents:

  1. Creating a view
  2. Loading a view
  3. Loading multiple views
  4. Adding dynamic data to the view
  5. Storing views within subdirectories
  6. Creating loops
  7. Returning views as data

Creating a view

  • Create a view file test.php and store it in the directory applications/views/ directory.
        <html>
         <head>
                 <title>Welcome to </title>
         </head>
         <body>
                 <h1>Welcome to my Blog!</h1>
         </body>
        </html>

Loading a view

  • The view will load from the controller.
  • Suppose if you need to load test.php in the applications/views/ directory, you need to call like as follows.
        $this->load->view('test');
  • If you visit the site URL, you can see the result.
        <?php
        class Test extends CI_Controller {
    
        public function index()
        {
                $this->load->view('test');
        }

Loading multiple views

  • For example, If you have a header view, a menu view, content view, and footer view. It will be loaded like this
        <?php
        class Page extends CI_Controller {
    
                public function index()
                {
                        $data['page_title'] = 'Your title';
                        $this->load->view('header');
                        $this->load->view('menu');
                        $this->load->view('content', $data);
                        $this->load->view('footer');
                }
    
        }

Storing views within subdirectories

  • If you prefer the type of organization, you can store the view files within the subdirectories.
       $this->load->view('directory_name/file_name');

Adding Dynamic Data to the View


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

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