structure-views.md 21.6 KB
Newer Older
Qiang Xue committed
1 2
Views
=====
Alexander Makarov committed
3

Qiang Xue committed
4 5 6 7 8
Views are part of the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) architecture.
They are responsible for presenting data to end users. In a Yii application, the view layer is composed by
[view templates](#view-templates) and [view components](#view-components). The former contains presentational
code (e.g. HTML), while the latter provides common view-related features and is responsible for turning view
templates into response content. We often use "views" to refer to view templates.
Qiang Xue committed
9

Qiang Xue committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

## View Templates

You turn a view template into response content by pushing [model](structure-models.md) data into
the template and rendering it. For example, in the `post/view` action below, the `view` template
is rendered with the `$model` data. The rendering result is a string which is returned by the action as the response content.

```php
namespace app\controllers;

use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{
    public function actionView($id)
    {
        $model = Post::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException;
        }

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

### Rendering Views in Controllers

### Rendering Views in Widgets

### Rendering Views in Views

### View Names

By default, a view template is simply a PHP script file (called *view file*). Like [models](structure-models.md)
and [controllers](structure-controllers.md), view files are usually organized under the so-called *view paths*.
For views rendered by controllers that directly belong to an application, they are located under the `@app/views` path.

* applications:
* modules:
* controllers:
* widgets and other components:

When rendering a view template, you can specify it using a view name, a view file path,
or an [alias](concept-aliases.md) to the view file path.

If a view name is used, it will be resolved into a view file path according to the current
[[yii\base\View::context|view context]] using one of the following rules:

* If the view name starts with double slashes `//`, the corresponding view file path is considered to be
  `@app/views/ViewName`. For example, `//site/about` will be resolved into `@app/views/site/about`.
* If the view name starts with a single slash `/`, the view file path is formed by prefixing the view name
  with the [[yii\base\Module::viewPath|view path]] of the currently active [module](structure-modules.md).
  If there is no active module, `@app/views/ViewName` will be used. For example, `/user/create` will be resolved into
  `@app/modules/user/views/user/create`, if the currently active module is `user`. If there is no active module,
  the view file path would be `@app/views/user/create`.
* If the view is rendered with a [[yii\base\View::context|context]], the view file path will be prefixed with
  the [[yii\base\ViewContextInterface::getViewPath()|view path]]. For example, `site/about` will be resolved
  into `@app/views/site/about` if the context is the `SiteController`.
* If a view was previously rendered, the directory containing that view file will be prefixed to
  the new view name.


## Layouts

### Nested Layouts


### Accessing Data

## View Components

## Creating Views

### Setting page title
### Adding meta tags
### Registering link tags
### Registering CSS
### Registering scripts
### Static Pages
### Assets

## Alternative Template Engines
Qiang Xue committed
98

Alexander Makarov committed
99 100 101 102

Basics
------

103 104 105 106
By default, Yii uses PHP in view templates to generate content and elements. A web application view typically contains
some combination of HTML, along with PHP `echo`, `foreach`, `if`, and other basic constructs.
Using complex PHP code in views is considered to be bad practice. When complex logic and functionality is needed,
such code should either be moved to a controller or a widget.
Alexander Makarov committed
107

108
The view is typically called from controller action using the [[yii\base\Controller::render()|render()]] method:
Alexander Makarov committed
109 110 111 112

```php
public function actionIndex()
{
113
    return $this->render('index', ['username' => 'samdark']);
Alexander Makarov committed
114 115 116
}
```

117 118
The first argument to [[yii\base\Controller::render()|render()]] is the name of the view to display.
In the context of the controller, Yii will search for its views in `views/site/` where `site`
Qiang Xue committed
119
is the controller ID. For details on how the view name is resolved, refer to the [[yii\base\Controller::render()]] method.
Alexander Makarov committed
120

121 122 123
The second argument to [[yii\base\Controller::render()|render()]] is a data array of key-value pairs.
Through this array, data can be passed to the view, making the value available in the view as a variable
named the same as the corresponding key.
124 125

The view for the action above would be `views/site/index.php` and can be something like:
Alexander Makarov committed
126 127

```php
128
<p>Hello, <?= $username ?>!</p>
Alexander Makarov committed
129 130
```

131
Any data type can be passed to the view, including arrays or objects.
Alexander Makarov committed
132

133 134 135 136 137 138 139 140 141 142 143
Besides the above [[yii\web\Controller::render()|render()]] method, the [[yii\web\Controller]] class also provides
several other rendering methods. Below is a summary of these methods:

* [[yii\web\Controller::render()|render()]]: renders a view and applies the layout to the rendering result.
  This is most commonly used to render a complete page.
* [[yii\web\Controller::renderPartial()|renderPartial()]]: renders a view without applying any layout.
  This is often used to render a fragment of a page.
* [[yii\web\Controller::renderAjax()|renderAjax()]]: renders a view without applying any layout, and injects all
  registered JS/CSS scripts and files. It is most commonly used to render an HTML output to respond to an AJAX request.
* [[yii\web\Controller::renderFile()|renderFile()]]: renders a view file. This is similar to
  [[yii\web\Controller::renderPartial()|renderPartial()]] except that it takes the file path
Qiang Xue committed
144 145 146
  of the view instead of the view name.


Alexander Makarov committed
147 148 149
Widgets
-------

150 151 152 153 154 155 156 157
Widgets are self-contained building blocks for your views, a way to combine complex logic, display, and functionality into a single component. A widget:

* May contain advanced PHP programming
* Is typically configurable
* Is often provided data to be displayed
* Returns HTML to be shown within the context of the view

There are a good number of widgets bundled with Yii, such as [active form](form.md),
Qiang Xue committed
158
breadcrumbs, menu, and [wrappers around bootstrap component framework](bootstrap-widgets.md). Additionally there are
159
extensions that provide more widgets, such as the official widget for [jQueryUI](http://www.jqueryui.com) components.
160

161
In order to use a widget, your view file would do the following:
162 163 164

```php
// Note that you have to "echo" the result to display it
Alexander Makarov committed
165
echo \yii\widgets\Menu::widget(['items' => $items]);
166 167

// Passing an array to initialize the object properties
Alexander Makarov committed
168
$form = \yii\widgets\ActiveForm::begin([
169 170
    'options' => ['class' => 'form-horizontal'],
    'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
Alexander Makarov committed
171
]);
172 173 174 175
... form inputs here ...
\yii\widgets\ActiveForm::end();
```

176 177 178
In the first example in the code above, the [[yii\base\Widget::widget()|widget()]] method is used to invoke a widget
that just outputs content. In the second example, [[yii\base\Widget::begin()|begin()]] and [[yii\base\Widget::end()|end()]]
are used for a
179 180 181
widget that wraps content between method calls with its own output. In case of the form this output is the `<form>` tag
with some properties set.

182

Alexander Makarov committed
183 184 185 186 187 188 189
Security
--------

One of the main security principles is to always escape output. If violated it leads to script execution and,
most probably, to cross-site scripting known as XSS leading to leaking of admin passwords, making a user to automatically
perform actions etc.

Qiang Xue committed
190
Yii provides a good tool set in order to help you escape your output. The very basic thing to escape is a text without any
Alexander Makarov committed
191 192 193 194 195 196 197 198
markup. You can deal with it like the following:

```php
<?php
use yii\helpers\Html;
?>

<div class="username">
199
    <?= Html::encode($user->name) ?>
Alexander Makarov committed
200 201 202 203
</div>
```

When you want to render HTML it becomes complex so we're delegating the task to excellent
Qiang Xue committed
204
[HTMLPurifier](http://htmlpurifier.org/) library which is wrapped in Yii as a helper [[yii\helpers\HtmlPurifier]]:
Alexander Makarov committed
205 206 207 208 209 210 211

```php
<?php
use yii\helpers\HtmlPurifier;
?>

<div class="post">
212
    <?= HtmlPurifier::process($post->text) ?>
Alexander Makarov committed
213 214 215 216 217 218 219 220 221
</div>
```

Note that besides HTMLPurifier does excellent job making output safe it's not very fast so consider
[caching result](caching.md).

Alternative template languages
------------------------------

222
There are official extensions for [Smarty](http://www.smarty.net/) and [Twig](http://twig.sensiolabs.org/). In order
Alexander Makarov committed
223
to learn more refer to [Using template engines](template.md) section of the guide.
Alexander Makarov committed
224

225 226
Using View object in templates
------------------------------
Alexander Makarov committed
227

228
An instance of [[yii\web\View]] component is available in view templates as `$this` variable. Using it in templates you
229
can do many useful things including setting page title and meta, registering scripts and accessing the context.
Alexander Makarov committed
230 231 232 233 234 235 236 237 238 239 240 241

### Setting page title

A common place to set page title are view templates. Since we can access view object with `$this`, setting a title
becomes as easy as:

```php
$this->title = 'My page title';
```

### Adding meta tags

242
Adding meta tags such as encoding, description, keywords is easy with view object as well:
Alexander Makarov committed
243 244

```php
Alexander Makarov committed
245
$this->registerMetaTag(['encoding' => 'utf-8']);
Alexander Makarov committed
246 247 248 249 250 251 252 253 254 255 256
```

The first argument is an map of `<meta>` tag option names and values. The code above will produce:

```html
<meta encoding="utf-8">
```

Sometimes there's a need to have only a single tag of a type. In this case you need to specify the second argument:

```html
257 258
$this->registerMetaTag(['name' => 'description', 'content' => 'This is my cool website made with Yii!'], 'meta-description');
$this->registerMetaTag(['name' => 'description', 'content' => 'This website is about funny raccoons.'], 'meta-description');
Alexander Makarov committed
259 260
```

Aris Karageorgos committed
261
If there are multiple calls with the same value of the second argument (`meta-description` in this case), the latter will
262
override the former and only a single tag will be rendered:
Alexander Makarov committed
263 264

```html
265
<meta name="description" content="This website is about funny raccoons.">
Alexander Makarov committed
266 267 268 269
```

### Registering link tags

270
`<link>` tag is useful in many cases such as customizing favicon, pointing to RSS feed or delegating OpenID to another
Alexander Makarov committed
271 272 273
server. Yii view object has a method to work with these:

```php
Alexander Makarov committed
274
$this->registerLinkTag([
275 276 277 278
    'title' => 'Lives News for Yii Framework',
    'rel' => 'alternate',
    'type' => 'application/rss+xml',
    'href' => 'http://www.yiiframework.com/rss.xml/',
Alexander Makarov committed
279
]);
Alexander Makarov committed
280 281 282 283 284 285 286 287 288 289 290 291
```

The code above will result in

```html
<link title="Lives News for Yii Framework" rel="alternate" type="application/rss+xml" href="http://www.yiiframework.com/rss.xml/" />
```

Same as with meta tags you can specify additional argument to make sure there's only one link of a type registered.

### Registering CSS

292 293
You can register CSS using [[yii\web\View::registerCss()|registerCss()]] or [[yii\web\View::registerCssFile()|registerCssFile()]].
The former registers a block of CSS code while the latter registers an external CSS file. For example,
Alexander Makarov committed
294 295 296 297 298 299 300 301 302 303 304 305 306

```php
$this->registerCss("body { background: #f00; }");
```

The code above will result in adding the following to the head section of the page:

```html
<style>
body { background: #f00; }
</style>
```

Anderson Müller committed
307
If you want to specify additional properties of the style tag, pass an array of name-values to the third argument.
Anderson Müller committed
308
If you need to make sure there's only a single style tag use fourth argument as was mentioned in meta tags description.
Alexander Makarov committed
309 310

```php
Qiang Xue committed
311
$this->registerCssFile("http://example.com/css/themes/black-and-white.css", [BootstrapAsset::className()], ['media' => 'print'], 'css-print-theme');
Alexander Makarov committed
312 313
```

Qiang Xue committed
314 315 316
The code above will add a link to CSS file to the head section of the page.

* The first argument specifies the CSS file to be registered.
317 318 319
* The second argument specifies that this CSS file depends on [[yii\bootstrap\BootstrapAsset|BootstrapAsset]], meaning it will be added
  AFTER the CSS files in [[yii\bootstrap\BootstrapAsset|BootstrapAsset]]. Without this dependency specification, the relative order
  between this CSS file and the [[yii\bootstrap\BootstrapAsset|BootstrapAsset]] CSS files would be undefined.
Qiang Xue committed
320 321 322 323 324 325
* The third argument specifies the attributes for the resulting `<link>` tag.
* The last argument specifies an ID identifying this CSS file. If it is not provided, the URL of the CSS file will be
  used instead.


It is highly recommended that you use [asset bundles](assets.md) to register external CSS files rather than
326 327
using [[yii\web\View::registerCssFile()|registerCssFile()]]. Using asset bundles allows you to combine and compress
multiple CSS files, which is desirable for high traffic websites.
Qiang Xue committed
328

Alexander Makarov committed
329 330 331

### Registering scripts

332 333 334 335
With the [[yii\web\View]] object you can register scripts. There are two dedicated methods for it:
[[yii\web\View::registerJs()|registerJs()]] for inline scripts and
[[yii\web\View::registerJsFile()|registerJsFile()]] for external scripts.
Inline scripts are useful for configuration and dynamically generated code.
Alexander Makarov committed
336
The method for adding these can be used as follows:
Alexander Makarov committed
337

Alexander Makarov committed
338
```php
339
$this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my-options');
Alexander Makarov committed
340 341
```

Qiang Xue committed
342 343
The first argument is the actual JS code we want to insert into the page. The second argument
determines where script should be inserted into the page. Possible values are:
Alexander Makarov committed
344

345 346 347 348 349
- [[yii\web\View::POS_HEAD|View::POS_HEAD]] for head section.
- [[yii\web\View::POS_BEGIN|View::POS_BEGIN]] for right after opening `<body>`.
- [[yii\web\View::POS_END|View::POS_END]] for right before closing `</body>`.
- [[yii\web\View::POS_READY|View::POS_READY]] for executing code on document `ready` event. This will register [[yii\web\JqueryAsset|jQuery]] automatically.
- [[yii\web\View::POS_LOAD|View::POS_LOAD]] for executing code on document `load` event. This will register [[yii\web\JqueryAsset|jQuery]] automatically.
Alexander Makarov committed
350

Qiang Xue committed
351 352
The last argument is a unique script ID that is used to identify code block and replace existing one with the same ID
instead of adding a new one. If you don't provide it, the JS code itself will be used as the ID.
Alexander Makarov committed
353

Qiang Xue committed
354
An external script can be added like the following:
Alexander Makarov committed
355 356

```php
Qiang Xue committed
357
$this->registerJsFile('http://example.com/js/main.js', [JqueryAsset::className()]);
Alexander Makarov committed
358 359
```

360 361
The arguments for [[yii\web\View::registerJsFile()|registerJsFile()]] are similar to those for
[[yii\web\View::registerCssFile()|registerCssFile()]]. In the above example,
Qiang Xue committed
362 363 364 365
we register the `main.js` file with the dependency on `JqueryAsset`. This means the `main.js` file
will be added AFTER `jquery.js`. Without this dependency specification, the relative order between
`main.js` and `jquery.js` would be undefined.

366 367
Like for [[yii\web\View::registerCssFile()|registerCssFile()]], it is also highly recommended that you use
[asset bundles](assets.md) to register external JS files rather than using [[yii\web\View::registerJsFile()|registerJsFile()]].
Qiang Xue committed
368

Alexander Makarov committed
369 370 371 372 373 374 375 376

### Registering asset bundles

As was mentioned earlier it's preferred to use asset bundles instead of using CSS and JavaScript directly. You can get
details on how to define asset bundles in [asset manager](assets.md) section of the guide. As for using already defined
asset bundle, it's very straightforward:

```php
377
\frontend\assets\AppAsset::register($this);
Alexander Makarov committed
378 379 380 381
```

### Layout

Alexander Makarov committed
382 383
A layout is a very convenient way to represent the part of the page that is common for all or at least for most pages
generated by your application. Typically it includes `<head>` section, footer, main menu and alike elements.
Reazul Iqbal committed
384
You can find a fine example of the layout in a [basic application template](apps-basic.md). Here we'll review the very
Alexander Makarov committed
385 386 387 388 389 390
basic one without any widgets or extra markup.

```php
<?php
use yii\helpers\Html;
?>
Алексей committed
391
<?php $this->beginPage() ?>
Alexander Makarov committed
392
<!DOCTYPE html>
393
<html lang="<?= Yii::$app->language ?>">
Alexander Makarov committed
394
<head>
395 396 397
    <meta charset="<?= Yii::$app->charset ?>"/>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
Alexander Makarov committed
398 399
</head>
<body>
Алексей committed
400
<?php $this->beginBody() ?>
401 402 403
    <div class="container">
        <?= $content ?>
    </div>
404
    <footer class="footer">&copy; 2013 me :)</footer>
Алексей committed
405
<?php $this->endBody() ?>
Alexander Makarov committed
406 407
</body>
</html>
Алексей committed
408
<?php $this->endPage() ?>
Alexander Makarov committed
409 410 411 412 413
```

In the markup above there's some code. First of all, `$content` is a variable that will contain result of views rendered
with controller's `$this->render()` method.

414
We are importing [[yii\helpers\Html|Html]] helper via standard PHP `use` statement. This helper is typically used for almost all views
415 416
where one need to escape outputted data.

417 418 419 420
Several special methods such as [[yii\web\View::beginPage()|beginPage()]]/[[yii\web\View::endPage()|endPage()]],
[[yii\web\View::head()|head()]], [[yii\web\View::beginBody()|beginBody()]]/[[yii\web\View::endBody()|endBody()]]
are triggering page rendering events that are used for registering scripts, links and process page in many other ways.
Always include these in your layout in order for the rendering to work correctly.
Alexander Makarov committed
421

422
By default layout is loaded from `views/layouts/main.php`. You may change it at controller or module level by setting
423
different value to `layout` property.
424 425

In order to pass data from controller to layout, that you may need for breadcrumbs or similar elements, use view component
Alexander Makarov committed
426
params property. In controller it can be set as:
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

```php
$this->view->params['breadcrumbs'][] = 'Contact';
```

In a view it will be:

```php
$this->params['breadcrumbs'][] = 'Contact';
```

In layout file the value can be used like the following:

```php
<?= Breadcrumbs::widget([
    'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
```

446 447 448 449 450 451 452 453 454 455 456
You may also wrap the view render result into a layout using [[yii\base\View::beginContent()]], [[yii\base\View::endContent()]].
This approach can be used while applying nested layouts:

```php
<?php $this->beginContent('//layouts/overall') ?>
<div class="content">
    <?= $content ?>
<div>
<?php $this->endContent() ?>
```

Alexander Makarov committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
### Partials

Often you need to reuse some HTML markup in many views and often it's too simple to create a full-featured widget for it.
In this case you may use partials.

Partial is a view as well. It resides in one of directories under `views` and by convention is often started with `_`.
For example, we need to render a list of user profiles and, at the same time, display individual profile elsewhere.

First we need to define a partial for user profile in `_profile.php`:

```php
<?php
use yii\helpers\Html;
?>

<div class="profile">
473 474
    <h2><?= Html::encode($username) ?></h2>
    <p><?= Html::encode($tagline) ?></p>
Alexander Makarov committed
475 476 477 478 479 480 481
</div>
```

Then we're using it in `index.php` view where we display a list of users:

```php
<div class="user-index">
482 483 484 485 486 487 488 489
    <?php
    foreach ($users as $user) {
        echo $this->render('_profile', [
            'username' => $user->name,
            'tagline' => $user->tagline,
        ]);
    }
    ?>
Alexander Makarov committed
490 491 492 493 494 495
</div>
```

Same way we can reuse it in another view displaying a single user profile:

```php
Alexander Makarov committed
496
echo $this->render('_profile', [
497 498
    'username' => $user->name,
    'tagline' => $user->tagline,
Alexander Makarov committed
499
]);
Alexander Makarov committed
500 501
```

502 503 504 505 506 507 508 509 510 511 512 513 514 515

When you call `render()` to render a partial in a current view, you may use different formats to refer to the partial.
The most commonly used format is the so-called relative view name which is as shown in the above example.
The partial view file is relative to the directory containing the current view. If the partial is located under
a subdirectory, you should include the subdirectory name in the view name, e.g., `public/_profile`.

You may use path alias to specify a view, too. For example, `@app/views/common/_profile`.

And you may also use the so-called absolute view names, e.g., `/user/_profile`, `//user/_profile`.
An absolute view name starts with a single slashes or double slashes. If it starts with a single slash,
the view file will be looked for under the view path of the currently active module. Otherwise, it will
will be looked for under the application view path.


Alexander Makarov committed
516 517 518 519 520 521 522 523 524 525
### Accessing context

Views are generally used either by controller or by widget. In both cases the object that called view rendering is
available in the view as `$this->context`. For example if we need to print out the current internal request route in a
view rendered by controller we can use the following:

```php
echo $this->context->getRoute();
```

Evgeniy Tkachenko committed
526 527
### Static Pages

528 529
If you need to render static pages you can use class `ViewAction`. It represents an action that displays a view according
to a user-specified parameter.
Evgeniy Tkachenko committed
530

531
Usage of the class is simple. In your controller use the class via `actions` method:
Evgeniy Tkachenko committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

```php
class SiteController extends Controller
{
    public function actions()
    {
        return [
            'static' => [
                'class' => '\yii\web\ViewAction',
            ],
        ];
    }

    //...
}
```

549 550
Then create `index.php` in `@app/views/site/pages/`:

Evgeniy Tkachenko committed
551 552
```php
//index.php
553
<h1>Hello, I am a static page!</h1>
Evgeniy Tkachenko committed
554 555
```

556
That's it. Now you can try it using `/index.php?r=site/static`.
Evgeniy Tkachenko committed
557 558

By default, the view being displayed is specified via the `view` GET parameter. 
559
If you open `/index.php?r=site/static?&view=about` then `@app/views/site/pages/about.php` view file will be used.
Evgeniy Tkachenko committed
560

561
If not changed or specified via GET defaults are the following:
Evgeniy Tkachenko committed
562

563 564 565 566
- GET parameter name: `view`.
- View file used if parameter is missing: `index.php`.
- Directory where views are stored (`viewPrefix`): `pages`.
- Layout for the page rendered matches the one used in controller.
Evgeniy Tkachenko committed
567

568
For more information see [[yii\web\ViewAction]].
Evgeniy Tkachenko committed
569

Alexander Makarov committed
570 571
### Caching blocks

Alexander Makarov committed
572
To learn about caching of view fragments please refer to [caching](caching.md) section of the guide.
573 574 575 576 577

Customizing View component
--------------------------

Since view is also an application component named `view` you can replace it with your own component that extends
578
from [[yii\base\View]] or [[yii\web\View]]. It can be done via application configuration file such as `config/web.php`:
579 580

```php
Alexander Makarov committed
581
return [
582 583 584 585 586 587 588
    // ...
    'components' => [
        'view' => [
            'class' => 'app\components\View',
        ],
        // ...
    ],
Alexander Makarov committed
589
];
590
```