Codeigniter 4 – Views with Examples

What is a View?

- A View is a file that contains the HTML and PHP code for displaying data to the user.
- Views are stored in the app/Views directory.

Creating a View

- Create a new file in the app/Views directory (e.g. user_view.php).
- Add HTML and PHP code to the file to display data.

Example: app/Views/user_view.php

<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1><?= $user->name ?></h1>
    <p><?= $user->email ?></p>
</body>
</html>

Passing Data to a View

- Use the view() function to render the View and pass data to it.
- Pass an array of data as the second argument to the view() function.

Example:

public function index()
{
    $data['user'] = $this->userModel->getUser(1);
    return view('user_view', $data);
}

View Variables

- View variables are the data passed to the View from the Controller.
- Access view variables using the $ symbol.

Example:

<h1><?= $user->name ?></h1>

View Helpers

- View helpers are functions that assist with displaying data in the View.
- Use the helper() function to load a View helper.

Example:

helper('form');
echo form_input('name', $user->name);

View Layouts

- View layouts are templates that contain common HTML code for multiple Views.
- Use the extend keyword to extend a layout in a View.

Example:

<?= extend('layouts/default') ?>

<?= section('content') ?>
    <h1>User Profile</h1>
    <p><?= $user->email ?></p>
<?= endSection() ?>

View Sections

- View sections are blocks of code that can be inserted into a layout.
- Use the section keyword to define a section in a View.

Example:

<?= section('header') ?>
    <h1>User Profile</h1>
<?= endSection() ?>

I hope this helps! Let me know if you have any further questions or need more information.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0