Views ===== 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. ## 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 Basics ------ 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. The view is typically called from controller action using the [[yii\base\Controller::render()|render()]] method: ```php public function actionIndex() { return $this->render('index', ['username' => 'samdark']); } ``` 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` is the controller ID. For details on how the view name is resolved, refer to the [[yii\base\Controller::render()]] method. 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. The view for the action above would be `views/site/index.php` and can be something like: ```php
Hello, = $username ?>!
``` Any data type can be passed to the view, including arrays or objects. 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 of the view instead of the view name. Widgets ------- 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), breadcrumbs, menu, and [wrappers around bootstrap component framework](bootstrap-widgets.md). Additionally there are extensions that provide more widgets, such as the official widget for [jQueryUI](http://www.jqueryui.com) components. In order to use a widget, your view file would do the following: ```php // Note that you have to "echo" the result to display it echo \yii\widgets\Menu::widget(['items' => $items]); // Passing an array to initialize the object properties $form = \yii\widgets\ActiveForm::begin([ 'options' => ['class' => 'form-horizontal'], 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']], ]); ... form inputs here ... \yii\widgets\ActiveForm::end(); ``` 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 widget that wraps content between method calls with its own output. In case of the form this output is the `