Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Views

A view is a file with the markup of a page. It separates HTML from controller code. Yii has no special template language: a view is a plain PHP file where markup alternates with short pieces of code.

Where a view lives

Views are stored in the views folder, and every controller has its own subfolder named after it as in the route: the views of PostController are in views/post. Create the folder and the file views/post/index.php by hand:

<!-- views/post/index.php -->
<h1>Posts</h1>
<p>The list of posts will be here.</p>

Rendering a view

An action calls the render() method with the file name without the extension:

// controllers/PostController.php
public function actionIndex(): string
{
    return $this->render('index');
}

Open /posts and the heading "Posts" appears inside the common site design with a header and a footer. That design is called a layout, and the next lesson is about it.

Passing data

Data is passed as the second argument of render(), an array:

public function actionIndex(): string
{
    $posts = [
        ['id' => 1, 'title' => 'First post'],
        ['id' => 2, 'title' => 'Second post'],
    ];
 
    return $this->render('index', ['posts' => $posts]);
}

The array keys become view variables: the posts key becomes the $posts variable.

<?php
// views/post/index.php
 
use yii\helpers\Html;
 
$this->title = 'Posts';
?>
 
<h1><?= Html::encode($this->title) ?></h1>
 
<?php if ($posts === []): ?>
    <p>No posts yet.</p>
<?php else: ?>
    <ul>
        <?php foreach ($posts as $post): ?>
            <li><?= Html::a(Html::encode($post['title']), ['post/view', 'id' => $post['id']]) ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

The page shows a list of two links to /posts/1 and /posts/2. The $this variable in a view is the view object; the layout prints $this->title in the browser tab title. Html::a() creates a link from a route.

Escaping

Html::encode() replaces the characters <, > and & with safe notations so that text does not turn into markup. Everything typed by a user or read from the database is printed through it.

Partial views

A repeated fragment is moved into a separate file whose name by convention starts with an underscore. Create views/post/_card.php:

<?php
// views/post/_card.php
 
use yii\helpers\Html;
?>
 
<article>
    <h2><?= Html::encode($post['title']) ?></h2>
</article>

In the main view the fragment is inserted like this: <?= $this->render('_card', ['post' => $post]) ?>. Here render() is called on the view and returns markup without the layout.

Common mistake

<?= $post['title'] ?> prints the value as it is. If the title contains a <script> tag, it will run in the visitor's browser. Yii does not escape output by itself, so wrap every value that is not ready-made markup in Html::encode().

Thanks for reading!

Donate to the site — we work hard for you.