For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Views in CodeIgniter 4

What are Views in CodeIgniter 4?

The View is responsible for the presentation of Model (data) in a certain format. A view is a simple web page created using HTML. We can call a view by using a Controller.

How to create a view?

<html>
<head>
        <title>About Us</title>
</head>
<body>
        <h1>infovistar.com</h1>
</body>
</html>

Save the file as about_us.php in your /app/Views directory.

How to load a view?

By using view() method we can load a view file in a Controller.

Load view in CodeIgniter 3 Load view in CodeIgniter 4
$this->load->view('about_us');
echo view('about_us');

Now we can set this view to our about_us method in the Home.php controller.

<?php
namespace App\Controllers;	

class Home extends BaseController {

	public function about_us() {
		echo view('about_us');
	}

}
?>

Add dynamic data to the View

We can pass data from the controller to the view by way of an array or an object in the second parameter of the view method.

Here is an example using an array:

$data = array(
        'title' => infovistar.com',
        'heading' => About Us',
        'message' => 'Welcome to CodeIgniter‘'
	);
echo view('about_us', $data);

/app/Controllers/Home.php

<?php
namespace App\Controllers;	

class Home extends BaseController {

	public function about_us() {
		$data = array(
		        'title' => 'infovistar.com',
		        'heading' => 'About Us',
		        'message' => 'Welcome to CodeIgniter'
			);
		echo view('about_us', $data);
	}

}
?>

/app/Views/about_us.php

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