Yii 2 支援多種視圖名稱格式,解析優先序如下:
.php 副檔名//site/about → @app/views/site/about.php(應用層級)/user/create → 模組視圖路徑或 @app/views/user/create.phpview → @app/views/ControllerID/view.php$this->render('report', ['foo' => 1]),視圖較不依賴上下文,優先推薦。$this->context(控制器)或 Yii::$app,彈性高但耦合度較高。// 內容視圖
$this->params['breadcrumbs'][] = 'About Us';
// 版面配置
<?= yii\widgets\Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
佈局同為視圖,預存放於 @app/views/layouts/。關鍵方法:
beginPage() / endPage():觸發頁面開始/結束事件head():在 <head> 產生佔位符,注入 meta、link 標籤beginBody() / endBody():在 <body> 首尾注入腳本兩階段決定:
$layout → 模組 $layout → 應用 $layout,找到第一個非 null 值。@app/views/layouts/main)、絕對路徑(/main)、相對路徑(main)、false(不使用佈局)。<?php $this->beginContent('@app/views/layouts/base.php'); ?>
...子佈局內容...
<?php $this->endContent(); ?>
// 內容視圖定義
<?php $this->beginBlock('block1'); ?>...內容...<?php $this->endBlock(); ?>
// 佈局中渲染
<?php if (isset($this->blocks['block1'])): ?>
<?= $this->blocks['block1'] ?>
<?php else: ?>預設內容<?php endif; ?>
片段快取中需保持動態的部分(如用戶名、CSRF Token),使用 renderDynamic():
<?php if ($this->beginCache($id)): ?>
...靜態內容...
<?= $this->renderDynamic('return Yii::$app->user->identity->name;') ?>
...靜態內容...
<?php $this->endCache(); ?>
theme 設定快速切換外觀FragmentCache Widget 實現局部頁面快取// 頁面標題
$this->title = 'My Page Title';
// 佈局中:<title><?= Html::encode($this->title) ?></title>
// Meta 標籤
$this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework']);
// 指定 key 避免重複
$this->registerMetaTag(['name' => 'description', 'content' => '...'], 'description');
// Link 標籤
$this->registerLinkTag([
'rel' => 'alternate',
'type' => 'application/rss+xml',
'href' => 'https://example.com/rss.xml',
]);
可掛載事件調整渲染結果:EVENT_BEFORE_RENDER、EVENT_AFTER_RENDER、EVENT_BEGIN_BODY、EVENT_END_BODY 等。
使用 yii\web\ViewAction,無需撰寫控制器動作即可對應 @app/views/site/pages/ 下的視圖檔案。