Application Structure
3.7. VIEWS 87 Rendering in Controllers
Within controllers, you may call the following controller methods to render views:
• render(): renders a named view and applies a layout to the rendering result.
• renderPartial(): renders a named view without any layout.
• renderAjax(): renders a named view without any layout, and injects all registered JS/CSS scripts and les. It is usually used in response to AJAX Web requests.
• renderFile(): renders a view specied in terms of a view le path or alias.
• renderContent(): renders a static string by embedding it into the currently applicable layout. This method is available since version 2.0.1.
For example,
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;
}
// renders a view named "view" and applies a layout to it return $this->render('view', [
'model' => $model, } ]);
}
Rendering in Widgets
Within widgets, you may call the following widget methods to render views.
• render(): renders a named view.
• renderFile(): renders a view specied in terms of a view le path or alias.
For example,
namespace app\components;
88 CHAPTER 3. APPLICATION STRUCTURE
use yii\base\Widget;
use yii\helpers\Html;
class ListWidget extends Widget { public $items = [];
public function run()
{ // renders a view named "list"
return $this->render('list', [ 'items' => $this->items, ]);
} }
Rendering in Views
You can render a view within another view by calling one of the following methods provided by the view component:
• render(): renders a named view.
• renderAjax(): renders a named view and injects all registered JS/CSS scripts and les. It is usually used in response to AJAX Web requests.
• renderFile(): renders a view specied in terms of a view le path or alias.
For example, the following code in a view renders the _overview.php view
le which is in the same directory as the view being currently rendered.
Remember that$this in a view refers to the view component:
<?= $this->render('_overview') ?>
Rendering in Other Places
In any place, you can get access to the view application component by the expressionYii::$app->viewand then call its aforementioned methods to ren-der a view. For example,
// displays the view file "@app/views/site/license.php"
echo \Yii::$app->view->renderFile('@app/views/site/license.php');
Named Views
When you render a view, you can specify the view using either a view name or a view le path/alias. In most cases, you would use the former because it is more concise and exible. We call views specied using names as named views.
A view name is resolved into the corresponding view le path according to the following rules:
3.7. VIEWS 89
• A view name may omit the le extension name. In this case,.phpwill be used as the extension. For example, the view nameabout corresponds to the le nameabout.php.
• If the view name starts with double slashes//, the corresponding view
le path would be @app/views/ViewName. That is, the view is looked for under the application's view path. For example, //site/about will be resolved into@app/views/site/about.php.
• If the view name starts with a single slash/, the view le path is formed by prexing the view name with the view path of the currently active module. If there is no active module, @app/views/ViewNamewill be used.
For example,/user/createwill be resolved into@app/modules/user/views /user/create.php, if the currently active module is user. If there is no active module, the view le path would be@app/views/user/create.php.
• If the view is rendered with a context and the context implements yii
\base\ViewContextInterface, the view le path is formed by prex-ing the view path of the context to the view name. This mainly applies to the views rendered within controllers and widgets. For example,
about will be resolved into @app/views/site/about.php if the context is the controller SiteController.
• If a view is rendered within another view, the directory containing the other view le will be prexed to the new view name to form the actual view le path. For example,item will be resolved into @app/views/post /item.phpif it is being rendered in the view @app/views/post/index.php. According to the above rules, calling$this->render('view')in a controllerapp
\controllers\PostControllerwill actually render the view le@app/views/post/
view.php, while calling$this->render('_overview')in that view will render the view le @app/views/post/_overview.php.
Accessing Data in Views
There are two approaches to access data within a view: push and pull.
By passing the data as the second parameter to the view rendering meth-ods, you are using the push approach. The data should be represented as an array of name-value pairs. When the view is being rendered, the PHP
extract() function will be called on this array so that the array is extracted into variables in the view. For example, the following view rendering code in a controller will push two variables to thereportview: $foo = 1and$bar = 2.
echo $this->render('report', [ 'foo' => 1,
'bar' => 2, ]);
The pull approach actively retrieves data from the view component or other objects accessible in views (e.g. Yii::$app). Using the code below as an example, within the view you can get the controller object by the expression
90 CHAPTER 3. APPLICATION STRUCTURE
$this->context. And as a result, it is possible for you to access any properties or methods of the controller in the report view, such as the controller ID shown in the following:
The controller ID is: <?= $this->context->id ?>
The push approach is usually the preferred way of accessing data in views, because it makes views less dependent on context objects. Its drawback is that you need to manually build the data array all the time, which could become tedious and error prone if a view is shared and rendered in dierent places.
Sharing Data among Views
The view component provides the params property that you can use to share data among views.
For example, in an about view, you can have the following code which species the current segment of the breadcrumbs.
$this->params['breadcrumbs'][] = 'About Us';
Then, in the layout le, which is also a view, you can display the breadcrumbs using the data passed along params:
<?= yii\widgets\Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params[' breadcrumbs'] : [],
]) ?>
3.7.3 Layouts
Layouts are a special type of views that represent the common parts of multiple views. For example, the pages for most Web applications share the same page header and footer. While you can repeat the same page header and footer in every view, a better way is to do this once in a layout and embed the rendering result of a content view at an appropriate place in the layout.
Creating Layouts
Because layouts are also views, they can be created in the similar way as normal views. By default, layouts are stored in the directory @app/views/
layouts. For layouts used within a module, they should be stored in theviews /layouts directory under the module directory. You may customize the default layout directory by conguring the yii\base\Module::$layoutPath property of the application or modules.
The following example shows how a layout looks like. Note that for illustrative purpose, we have greatly simplied the code in the layout. In
3.7. VIEWS 91