Views in CodeIgniter

📘 CodeIgniter 👁 36 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Views in CodeIgniter (CodeIgniter 4)

Views are responsible for the presentation layer of your application. They contain HTML (and minimal PHP) and display data passed from controllers.


1. What Is a View?

  • Handles UI/output

  • Contains HTML, CSS, and minimal PHP

  • Does not contain business logic

  • Loaded by controllers


2. View Location

app/Views/

3. Creating a View

Create a file:

app/Views/home.php

Welcome to CodeIgniter

This is the home page.


4. Loading a View from Controller

public function index() { return view('home'); }

5. Passing Data to Views

Controller

public function profile() { $data = [ 'name' => 'John', 'age' => 25 ]; return view('profile', $data); }

View (profile.php)

Name: <?= esc($name) ?>

Age: <?= esc($age) ?>

esc() prevents XSS attacks.


6. Using Layouts (Header & Footer)

Header

<!-- app/Views/layout/header.php --> <!DOCTYPE html> <html> <head> <title><?= esc($title ?? 'My App') ?></title> </head> <body>

Footer

<!-- app/Views/layout/footer.php --> </body> </html>

Load in View

<?= $this->include('layout/header') ?>

Home Page

<?= $this->include('layout/footer') ?>

7. View Layouts & Sections (Recommended)

Layout File

<!-- app/Views/layout/main.php --> <!DOCTYPE html> <html> <body> <?= $this->renderSection('content') ?> </body> </html>

View File

<?= $this->extend('layout/main') ?> <?= $this->section('content') ?>

Dashboard

<?= $this->endSection() ?>

8. Conditional Logic in Views

<?php if ($isLoggedIn): ?>

Welcome back!

<?php else: ?>

Please login

<?php endif; ?>

9. Looping Data in Views

    <?php foreach ($users as $user): ?>
  • <?= esc($user['name']) ?>
  • <?php endforeach; ?>

10. Loading View with Subfolders

app/Views/admin/dashboard.php
return view('admin/dashboard');

11. View Helpers

Load helpers:

helper('url');

Use:


12. Best Practices

✅ Keep logic minimal
✅ Use layouts & sections
✅ Escape output with esc()
❌ Avoid database queries in views


Summary

  • Views handle presentation

  • Stored in app/Views

  • Data passed from controllers

  • Support layouts, sections, and helpers


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes