Views and View Cells
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
In CodeIgniter 4, Views are the presentation layer of your application, responsible for displaying information to the user. A View is typically a simple PHP file containing HTML and minimal PHP to display data passed to it from a Controller. This separation of concerns ensures that your business logic is kept separate from your presentation markup, leading to cleaner and more maintainable code.
For more complex, reusable page components, CodeIgniter provides View Cells. A View Cell is a self-contained unit that has its own logic (a class method) and its own view. This allows you to build widgets like a "latest news" block or a "shopping cart" display that can be easily rendered anywhere in your application, with their output optionally cached for performance. This documentation covers the creation and usage of both standard Views and component-based View Cells.
Sources: source/outgoing/views.rst:10-15, source/outgoing/view_cells.rst:12-18
Core View System
The core of the presentation layer revolves around the View Renderer service, which handles loading view files, passing data to them, and rendering the final HTML.
Sources: source/outgoing/view_renderer.rst
Creating and Rendering Views
A view is a file located in the app/Views/ directory. It contains the HTML structure of a page or a page fragment.
To render a view, you use the view() function, typically from within a Controller method. The first parameter is the name of the view file (without the .php extension).
// In a Controller
public function index()
{
return view('some_name');
}
This code would load the file at app/Views/some_name.php and send the results to the browser.
Sources: source/outgoing/views.rst:25-35
Passing Data to Views
Data can be passed from the controller to the view via an array as the second parameter of the view() function. The array keys are converted into variables within the view file.
Controller:
public function index()
{
$data = [
'title' => 'My Page Title',
'heading' => 'Welcome to my page!',
];
return view('blog_view', $data);
}
View (app/Views/blog_view.php):
<!DOCTYPE html>
<html>
<head>
<title><?= esc($title) ?></title>
</head>
<body>
<h1><?= esc($heading) ?></h1>
</body>
</html>
It is highly recommended to use the esc() function to escape data on output to prevent XSS attacks.
Sources: source/outgoing/views.rst:70-95
View Rendering Flow
The following diagram illustrates the basic flow of rendering a view from a controller.
View Options
The third parameter of the view() function is an array of options that can affect the rendering process.
| Option | Description | Default |
|---|---|---|
cache | The number of seconds to cache the view for. | null (disabled) |
saveData | If true, data is retained for subsequent view() calls. | false |
debug | If true, the CodeIgniter debug toolbar will be shown. | CI_DEBUG constant |
Sources: source/outgoing/views.rst:130-150
View Layouts
To maintain a consistent look and feel across your site, you can use View Layouts. This allows you to define a master template (e.g., with a header and footer) and have your views "fill in" specific sections.
A layout view uses $this->renderSection('section_name') to mark a replaceable area. A content view uses $this->extend('layout_file') to specify its layout and wraps content in $this->section('section_name') and $this->endSection().
Layout File (app/Views/layouts/default.php):
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
</head>
<body>
<header>
<h1>Main Header</h1>
</header>
<?= $this->renderSection('content') ?>
<footer>
<p>© 2023</p>
</footer>
</body>
</html>
Content View (app/Views/pages/about.php):
<?= $this->extend('layouts/default') ?>
<?= $this->section('content') ?>
<h2>About Us</h2>
<p>This is the about page content.</p>
<?= $this->endSection() ?>
The rendering engine combines these to produce the final HTML.
Sources: source/outgoing/view_layouts.rst:20-60
Layout Rendering Process
This diagram shows how a content view is merged into a layout.
View Parser
For simple variable substitution, CodeIgniter offers a View Parser. It uses a pseudo-template language, which is faster than a regular PHP view because it does simple string replacement instead of executing PHP code.
To use the parser, you call the parse() method from the parser service.
Controller:
public function index()
{
$data = [
'blog_title' => 'My Blog Title',
'blog_heading' => 'My Blog Heading',
];
return service('parser')->setData($data)->render('blog_template');
}
Template (app/Views/blog_template.php):
<html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h1>{blog_heading}</h1>
</body>
</html>
The parser supports simple variables, variable pairs for loops, and conditional logic.
Sources: source/outgoing/view_parser.rst:15-45
View Cells
View Cells are a powerful feature for creating reusable, component-like sections of your output. They encapsulate their own logic and view, making them ideal for widgets like a shopping cart, a login form, or a list of recent posts.
Sources: source/outgoing/view_cells.rst:12-18
Creating a View Cell
A cell consists of a class and an optional view file. The class is responsible for any logic needed to generate the data for its view.
- Create the Cell Class: Create a new class in a directory like app/Cells/. The class can have any public methods, which will be callable. These methods should return the rendered view string.
- Create the View: Create a corresponding view file in app/Cells/.
Example Cell Class (app/Cells/NoticeCell.php):
namespace App\Cells;
class NoticeCell
{
public function show(string $message): string
{
return view('App\Cells\notice_view', ['message' => $message]);
}
}
Example Cell View (app/Cells/notice_view.php):
<div class="alert alert-info">
<?= esc($message) ?>
</div>
Sources: source/outgoing/view_cells.rst:40-75
Using a View Cell
You can render a cell in any view using the global view_cell() function. You specify the class and method to call, along with any parameters.
view_cell('Namespace\ClassName::methodName', $params, $cache_duration, $cache_name);
Example Usage (in any view file):
<?= view_cell('App\Cells\NoticeCell::show', ['message' => 'This is a dynamic notice.']) ?>
This will instantiate NoticeCell, call the show() method with the provided message, and inject the returned HTML at that location.
Sources: source/outgoing/view_cells.rst:80-100
View Cell Execution Flow
The sequence diagram below shows the process of rendering a View Cell.
Caching Cell Output
One of the most powerful features of View Cells is their ability to be cached. If a cell's output doesn't change frequently, you can cache it for a set period of time to improve performance. This is done by passing a number of seconds as the third argument to view_cell().
// Cache the output of this cell for 5 minutes (300 seconds)
<?= view_cell('App\Cells\RecentPosts::list', [], 300) ?>
On the first run, the cell's method is executed and the output is stored in the cache. On subsequent requests within the 300-second window, the cached output is served directly without executing the cell's logic again.
Sources: source/outgoing/view_cells.rst:125-140
Conclusion
CodeIgniter's presentation layer is both simple and powerful. Standard Views provide a straightforward way to separate application logic from display markup. View Layouts enable consistent page templating, while the View Parser offers a simple, fast alternative for basic variable substitution. For building complex, reusable, and performant page components, View Cells offer an elegant and encapsulated solution with built-in caching capabilities, making them a cornerstone of modern application development in CodeIgniter 4.
Sources: source/outgoing/views.rst, source/outgoing/view_cells.rst, source/outgoing/view_layouts.rst