CodeIgniter 4 How To Work with Views And Layouts Tutorial

Reading Time: 9 minutes
19,907 Views

Inside this article we will see the concept i.e CodeIgniter 4 How To Work with Views And Layouts Tutorial. Article contains the classified information about View Layouts, Master layouts, etc.

Views and Layouts are the major part of user interface (UI). Inside this article we will see complete details of CodeIgniter 4 Views and layouts. Here, we will cover the followings –

  • Render a View file
  • Passing Data to a view file
  • Create Parent layout i.e Master Layout
  • Adding Styles & Scripts to layout
  • Include Partial files

This tutorial is going to give you the idea of views and layouts in CodeIgniter 4 application. This will be very interesting to learn see.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

How to Render a View File in CodeIgniter 4?

In CodeIgniter 4, we have a helper function called view() which is used to render a view file. Additionally, if we want to pass data inside file we can also pass view passing an array of values to view() function.

View files, we create and store into /app/Views folder.

Let’s see in action.

//...

$routes->get("first-route", function () {
    
    return view("my-file");
});

//...

First of all, we define application routes into /app/Config/Routes.php file. So here, we have a closure route, if you are interested to learn about CodeIgniter 4 Routing, click here.

Inside above route, we are calling a view file called my-file.php.

Also we can set it inside controller we can load in the same pattern via view() function.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Sample extends BaseController
{
    public function myView()
    {
        return view("my-file");
    }
}

We can see, we have used view() function into controller named as Sample. If file is inside any sub folder then calling a view file like this – view(“subfolder/file-name”)


Passing Data to View File

//...

$routes->get("first-route", function () {
    
    # Method #1
    $data = ["name" => "Sanjay", "email" => "sanjay@gmail.com"];
    return view("my-file", $data);
  
    # Method #2
    $data["name"] = "Sanjay";
    $data["email"] = "sanjay@gmail.com";
    return view("my-file", $data);
  
    # Method #3
    $name = "Sanjay"; $email = "sanjay@gmail.com";
    return view("my-file", compact("name", "email"));
});

//...

We can see we have different different ways to do the same task of passing data to a view file. At view file we need to use name key of array as $name as a variable and email as $email as a variable.


Create a Master Layout in CodeIgniter 4

Creating a Master Layout means the layout which will used by other view files. But the common things will remains same only the content will change according to view files.

Let’s first see how can we create a master layout?

Create a folder named as layout in /app/Views. Also create a file with the name master.php into it.

<html>

     <head>

        <title>Site Title</title>

     </head>

     <body>
        <!--Area for dynamic content -->
        <?= $this->renderSection("content"); ?>

     <body>

</html>
          
  • We have a line of code as $this->renderSection(“content”);. This is section or we can say a placeholder to place dynamic value which comes from the individual view files. content is only the key name. You can choose your own.

Let’s extend this layout to other view files.

Need to create say about-us.php inside /app/Views folder.

<?=$this->extend("layout/master")?>

<?=$this->section("content")?>

<h1>Welcome to About us page</h1>
<p>
    This is a sample page of our website
</p>

<?=$this->endSection()?>
  
  • Extend the master layout what we have created $this->extend(“layout/master”) layout is the folder name and master indicates master.php file inside it.
  • Remember $this->section(“content”) content is the key and also it’s a placeholder So now we are going to use that place and put dynamic content account to page. We need to open section and end section as well to define it.

Rendered output of the page as –

<html>

     <head>

        <title>Site Title</title>

     </head>

     <body>
        <!--Area for dynamic content -->
        <h1>Welcome to About us page</h1>
        <p>
            This is a sample page of our website
        </p>

     <body>

</html>
          

We can define more than one sections to render content in master layout. Now, let’s see how can we add style and script files into the master layout.


Including Styles and Scripts to CodeIgniter 4 Layout

We will see how can we add stylesheets and javascript files to master layout directly as well as if we need for specific files so how can do that.

<html>

     <head>
  
        <title>Site Title</title>

        <link rel="stylsheet" href="<?= base_url('public/css/style.css') ?>"/>
  
        <?= link_tag('public/css/style.css') ?>
  
     </head>

     <body>

       <?=$this->renderSection("content")?>

      <script src="<?= base_url('public/js/script.js') ?>"></script>
  
      <?= script_tag('public/js/script.js') ?>

     <body>

</html>
  
  • To add styles and scripts we have two options, either we can use HTML link/script tag with base_url or site_url helper functions of URL helper. Secondly we can use HTML helper of CodeIgniter 4.
  • public/css/style.css this is the path of style.css which we have placed at public folder and css folder inside it. Same goes for this as well public/js/script.js
  • HTML helper functions we have link_tag() & script_tag(). Passing file path inside it generates HTML tags into the output screen. Before use, we need to load html helper inside controller file or BaseController file.
<html>

     <head>

        <title>Site Title</title>

     </head>

     <body>
        <!--Area for dynamic content -->
        <?= $this->renderSection("content"); ?>
          
        <?= $this->renderSection("scripts"); ?>

     <body>

</html>

Loading Individual scripts of views to Master

<?=$this->extend("layout/master")?>

<?=$this->section("content")?>
<h1>Welcome to About us page</h1>
<?=$this->endSection()?>
  
<?=$this->section("scripts")?>
<script src="<?= base_url('public/js/script.js') ?>"></script>
<?=$this->endSection()?>
  

In some cases, if we need to attach partial files like some piece of header, footer, sidebar etc files. So how can we add into master layout.


Including Partial Files Or Sub views

We need to use include() method for it. This is not only for attaching sub views to master layout instead even we can attach to other view files as well.

Let’s see the use of it.

<html>

     <head>
  
        <title>Site Title</title>
  
     </head>

     <body>

       <?=$this->include("partials/header")?>

       <?=$this->renderSection("content")?>

      <?=$this->include("partials/footer")?>

     <body>

</html>
  • $this->include(“partials/header”) including sub view header from partials folder of /app/Views
  • $this->include(“partials/footer”) including sub view footer from partials folder of /app/Views

We hope this article helped you to learn about CodeIgniter 4 How To Work with Views And Layouts Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more

1 thought on “CodeIgniter 4 How To Work with Views And Layouts Tutorial”

  1. Nicely explained execution of sectionRender but the thing which i’m not able to get that what is the core difference in view cells, section render and include. Purpose is same for all three options (loading a view inside a view to make code clear and concise) but why three different options for same thing? is there any performance difference in all of these?

Comments are closed.