arrow_back
Back

Yii2 views and layouts: rendering, params, and blocks

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Key points about views:

  1. A view is just a file containing HTML and PHP code.
  2. Views rendered from a controller live in @app/views/ControllerID by default.

Example of view paths for given controllers:

Controller Path to views
PostController @app/views/post
PostCommentController @app/views/post-comment

The root view file is called a layout, and the files included into it are views.

Rendering a view

Rendering with parameters:

return $this->render('view', [
    'model' => $model,
]);

Or using compact():

return $this->render('view', compact('model', 'names'));

Layout

The default layout lives at views/layouts/main.php.

The rendered view is available in the $content variable:

<?= $content ?>

The layout can be changed in a controller (or in a single action):

public $layout = 'test';

Now the layout path is views/layouts/test.php.

Passing parameters from a view to the layout

Inside a view file, $this refers to a yii\web\View object — the same object is used in the layout, so parameters can be passed through it.

In the view:

$this->params['test'] = 'Hello';

In the layout:

<?php echo $this->params['test'] ?>

Passing blocks

Define a block in the view (it is not rendered in place):

<?php $this->beginBlock('testblock'); ?>
    ... some text
<?php $this->endBlock(); ?>

And output it in the layout:

<?= $this->blocks['testblock'] ?? 'Empty'; ?>

Paths to files

Use aliases instead of hardcoded paths:

Url::to('@web/images/logo.svg');
<?= Html::img('@web/images/logo.svg', ['alt' => 'Image']); ?>
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 helpers: Html, Url, dropdown lists, and formatter

arrow_forward