CodeIgniter 4 Views And Layouts

Share this Article

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

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Step by Step Let’s get started to CodeIgniter 4 Views.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# 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.

//.. Other routes

$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, if we go 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-view");
    }
}

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

//.. Other routes

$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 /app/Views/about-us.php

<?=$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.
<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 Views and Layouts in a very detailed way.

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.

Find More on CodeIgniter 4 here

1 thought on “CodeIgniter 4 Views And Layouts”

  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?

    Reply

Leave a Comment