View ==== View is an important part of MVC and is responsible for presenting data to end users. Basics ------ Yii uses PHP in view templates by default so in a web application a view typically contains some HTML, `echo`, `foreach` and such basic constructs. It may also contain widget calls. Using complex code in views is considered a bad practice. Such code should be moved to controller or widgets. View is typically called from controller action like the following: ```php public function actionIndex() { return $this->render('index', array( 'username' => 'samdark', )); } ``` First argument is the view name. In context of the controller Yii will search for its views in `views/site/` where `site` is controller ID. For details on how view name is resolved please refer to [yii\base\Controller::render] method. Second argument is data array that contains key-value pairs. Value is available in the view as a variable named the same as the corresponding key. So the view for the action above should be in `views/site/index.php` and can be something like: ```php
Hello, !
``` Instead of just scalar values you can pass anything else such as arrays or objects. Widgets ------- Widgets are a self-contained building blocks for your views. A widget may contain advanced logic, typically takes some configuration and data and returns HTML. There is a good number of widgets bundled with Yii such as [active form](form.md), breadcrumbs, menu or [wrappers around bootstrap component framework](boostrap-widgets.md). Additionally there are extensions providing additional widgets such as official one for jQueryUI components. In order to use widget you need to do the following: ```php // Note that you have to "echo" the result to display it echo \yii\widgets\Menu::widget(array('items' => $items)); // Passing an array to initialize the object properties $form = \yii\widgets\ActiveForm::begin(array( 'options' => array('class' => 'form-horizontal'), 'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), )); ... form inputs here ... \yii\widgets\ActiveForm::end(); ``` In the code above `widget` method is used for a widget that just outputs content while `begin` and `end` are used for a widget that wraps content between method calls with its own output. In case of the form this output is the `