Key points about views:
- A view is just a file containing HTML and PHP code.
- Views rendered from a controller live in
@app/views/ControllerIDby 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']); ?>
Andrew Dorokhov