Views
A view (template) is a file with HTML markup into which data is inserted. The controller prepares the data, the view is responsible only for how it looks. CodeIgniter views are ordinary PHP files in the app/Views folder; there is no separate template language.
The first view
There is no command for views — the file is created by hand. Create the folder app/Views/posts and the file index.php inside it:
<!-- app/Views/posts/index.php -->
<h1>Posts</h1>
<p>The list of posts will be here.</p>The view() function in the controller outputs the view:
// app/Controllers/Posts.php
public function index(): string
{
return view('posts/index');
}Open /posts and the heading "Posts" appears. The view name is written relative to app/Views and without the .php extension.
Passing data
The second argument of view() is an array. Its keys become variables of the view:
public function index(): string
{
$posts = [
['id' => 1, 'title' => 'First post'],
['id' => 2, 'title' => 'Second post'],
];
return view('posts/index', ['posts' => $posts]);
}For now the posts are written right in the code; in the second chapter they come from the database.
Output and loops
<?= ... ?> prints a value. Loops and conditions in views use the colon form:
<!-- app/Views/posts/index.php -->
<h1>Posts</h1>
<?php if ($posts === []): ?>
<p>No posts yet.</p>
<?php else: ?>
<ul>
<?php foreach ($posts as $post): ?>
<li>
<a href="<?= url_to('posts.show', $post['id']) ?>"><?= esc($post['title']) ?></a>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>The /posts page shows a list of two links. url_to() builds the addresses from the posts.show route name of the previous lessons.
Escaping
The esc() function turns dangerous characters into safe text: the angle brackets of a tag become visible characters instead of markup. The second argument names the place where the value is inserted:
| Call | Where to use |
|---|---|
esc($text) | Text between tags |
esc($text, 'attr') | An attribute value |
esc($text, 'js') | A string inside JavaScript |
Common mistake
<?= $post['title'] ?> without esc() prints the value as is: a script tag in the title would run in the visitor's browser. CodeIgniter does not escape output automatically — wrap every value that came from a user or from the database in esc().