How to Create and Load View in CodeIgniter

A view is an HTML or PHP file in the CodeIgniter which is used to display output on the browser.

From where the user can interact with the website and perform actions.

Views are loaded by the controller and one view can load other views on the page.

In this tutorial, I create a simple demonstration where I create a view and load it from the controller.

How to Create and Load View in CodeIgniter


Contents

  1. Create View
  2. Load View
  3. Demo
  4. Conclusion

1. Create View

View files are created and managed in application/views directory.

Create a home_view.php file application/views/ directory and create a simple HTML form.

The $content variable is initialized from the controller.

Completed Code

<!doctype html>
<html>
  <head>
    <title>Home Page</title>
  </head>
  <body>
    <h2><?= $content; ?></h2>
    <table>
      <tr>
        <td>Name : </td>
        <td><input type='text' /></td>
      </tr>
      <tr>
        <td>Username : </td>
        <td><input type='text' /></td>
      </tr>
      <tr>
        <td>Email : </td>
        <td><input type='text' /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type='button' value='Submit' /></td>
      </tr>
    </table>
 </body>
</html>

2. Load View

Create a User.php file in application/controllers/ directory.

Set Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

To display the view on the screen need to load the view from the controller using $this->load->view() method.

Pass the name of view file in the method e.g. $this->load->view('home_view').

Pass Data to View

To also pass the value to the view for this create an Array and initialize the values and pass in the method with view name e.g. $this->load->view('home_view',$data).

Don’t pass the second parameter in the method if you do not want to pass any value to view.

NOTE – If you have created an HTML file e.g. home_view.html then required to pass the file name with extension in $this->load->view('home_view.html') method otherwise the file would not load and display an error on the screen.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct() {

    parent::__construct();

    // load base_url
    $this->load->helper('url');
  }

  public function index(){

    $data['content'] = "Home Page";
    // load view
    $this->load->view('home_view',$data);
 
  }

}

3. Demo


4. Conclusion

You can use PHP or HTML file to create the view and load it from the controller using $this->load->view() method.

But make sure to pass the file name with extension if the view is an HTML file.

If you found this tutorial helpful then don't forget to share.