agyanadda@gmail.com

CodeIgniter 4 Views and Layouts

CodeIgniter 4 Basics 1 min read Updated Dec 3, 2026 Topic 8 of 30

Views are PHP files in app/Views that produce HTML. Load them with view('name', $data).

Printing data safely

Always use esc(): <?= esc($title) ?>. It escapes HTML and protects against XSS attacks.

Alternative syntax

Views read better with the colon syntax:

  • <?php foreach ($posts as $post): ?> ... <?php endforeach ?>
  • <?php if ($user): ?> ... <?php else: ?> ... <?php endif ?>

Layouts

Write the page frame once, for example app/Views/layouts/main.php, with <?= $this->renderSection('content') ?> where the page content goes.

Each page starts with <?= $this->extend('layouts/main') ?> and fills the section between <?= $this->section('content') ?> and <?= $this->endSection() ?>.

Including partials

<?= $this->include('partials/navbar') ?> inserts another view (navbar, footer).

View cells

For small reusable blocks that load their own data (like "latest posts" in a sidebar), use View Cells: <?= view_cell('LatestPosts') ?>.

Example

Example — Layout and page PHP
<!-- app/Views/layouts/main.php -->
<!DOCTYPE html>
<html>
<head><title><?= esc($title ?? 'My Site') ?></title></head>
<body>
  <?= $this->include('partials/navbar') ?>
  <main>
    <?= $this->renderSection('content') ?>
  </main>
</body>
</html>

<!-- app/Views/posts/index.php -->
<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
  <h1><?= esc($title) ?></h1>
  <?php foreach ($posts as $post): ?>
    <p><?= esc($post) ?></p>
  <?php endforeach ?>
<?= $this->endSection() ?>

The final page has the layout's <head>, the navbar partial, and the posts list inside <main>. The layout is written once and reused by every page.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function escapes output in a view?

Exercise 2 True / False

A page uses $this->extend('layouts/main') to use a layout.

Exercise 3 Fill in the Blank

The layout marks where page content goes with $this->___('content').

Frequently Asked Questions

CodeIgniter uses plain PHP views with layouts, sections and view cells, so there is nothing new to learn. It also includes a simple Parser class for {variable} style templates if you prefer that.