CI 4 What are Views?

View files are the frontend pages which a user sees. 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.) if you need this type of hierarchy.

As we discussed welcome_message.php is the default view layout file in application.

All the HTML code will be in view files. Views will be stored inside /app/Views folder.

There is no naming convention to create a view file. You can create with your own name and include .php with it.

Create First View

Create a file with any name say my-page.php inside /app/Views folder.

Open file and write this code into it.

<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>Welcome to my Page!</h1>
</body>
</html>
  

Load in controller

Open any controller from your application say Home.php. Add a method into that controller and link your view file.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	//...
	
	public function aboutUs()
	{
		return view('my-page');
	}

	//...
}

Loading Multiple Views

Let’s say we have multiple view files like header.php, sidebar.php, content.php, & footer.php. So how can we load multiple view files into method of controller.

Here is the way to do that.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	//...

	public function aboutUs()
	{
		echo view('header');

		echo view('sidebar');

		echo view('content');

		echo view('footer');
	}

	//...
}

Views from sub-directories

So far we placed all view files inside /app/Views. If we want to keep our view files inside any of the created sub-directories. So how can we link with controller?

Say we have a include folder inside /app/Views folder. Inside this include folder all we have the views like header.php, sidebar.php & footer.php

Syntax

echo view('directory_name/file_name');

To link all these files –

<?php

namespace App\Controllers;

class Home extends BaseController
{
	//...

	public function aboutUs()
	{
		echo view('include/header');

		echo view('include/sidebar');

		echo view('content');

		echo view('include/footer');
	}

	//...
}