In this tutorial, I will show you how we can create and load a view in CodeIgniter 4.

Contents

  1. Create CSS file
  2. Create View
  3. Load View
  4. Route
  5. Output
  6. Conclusion


1. Create CSS file

Create a CSS folder in the project public folder and create a style.css file.

Completed Code

body{
   background-color: whitesmoke;
}

h2{
   text-align: center;
}

table{
   margin: 0 auto;
}


2. Create View

Create a user_view.php file in the app/Views/ folder.

Direct access to files stored in the public folder to install To insert a publicly saved style.css file stored in the public/folder just forward the path.

The $content variable starts from User controller $data Array.

Completed Code

<!doctype html>
<html>
<head>
   <title>Home Page</title>

   <!-- CSS file -->
   <link rel="stylesheet" type="text/css" href="css/style.css">
</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> </td>
        <td><input type='button' value='Submit' /></td>
     </tr>
   </table>
</body>
</html>


3. Load View

Syntax –

To load view use return view().

return view('view-name',[Array]);
  • 1st parameter is the filename of the view.
  • 2nd parameter is optional. Used to transfer data to file viewing. It takes Array.

NOTE - If the view file is stored in a subfolder and you have access to it as follows - restore view ('subfolder1/viewname');.

Create Controller

Create a User.php file in the app/Controllers/ folder.

Create one way -

       index () - Upload views using this method. With Array data for viewing data.

$data['content'] = "Home Page";

View file, available using $content.

Pass user_view name and $data Array in return view().

NOTE - If you are using an HTML file for viewing then you need to call the view name with an extension e.g. restore view ('user_view.html');.

Completed Code

<?php namespace AppControllers;

class User extends BaseController
{
   public function index() {
      $data['content'] = "Home Page";
      return view('user_view',$data);
   }
}
?>

4. Route

Open app/Config/Routes.php file.

Update default controller to User –

$routes->setDefaultController('User');

Replace following route –

$routes->get('/', 'Home::index');

with this –

$routes->get('/', 'User::index');

Here, User is the controller name and index is the method name.


5. Output

Navigate to the project folder using CMD if you are on Windows or using the terminal if you are on Mac or Linux.

Issue the following command -

php spark serve

Run - http: // localhost: 8080/ browser.


6. Conclusion

You can use a PHP or HTML file to view. Use a keyword to access the excess Array value in the view file.