首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Yii 2 視圖進階技巧:佈局、區塊、動態內容與主題系統深度解析

     編輯:PHP 相關知識

視圖名稱解析規則

Yii 2 支援多種視圖名稱格式,解析優先序如下:

  • 省略 .php 副檔名
  • //site/about → @app/views/site/about.php(應用層級)
  • /user/create → 模組視圖路徑或 @app/views/user/create.php
  • 控制器/Widget 內部:view → @app/views/ControllerID/view.php
  • 視圖渲染視圖:相對於當前視圖目錄

資料傳遞:推送 vs 拉取

  • 推送:$this->render('report', ['foo' => 1]),視圖較不依賴上下文,優先推薦。
  • 拉取:視圖主動存取 $this->context(控制器)或 Yii::$app,彈性高但耦合度較高。

視圖間共享資料:params 屬性

// 內容視圖
$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> 首尾注入腳本

佈局選擇機制

兩階段決定:

  1. 依序檢查控制器 $layout → 模組 $layout → 應用 $layout,找到第一個非 null 值。
  2. 解析路徑:別名(@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(); ?>

View 元件進階功能

  • 主題系統:透過 theme 設定快速切換外觀
  • 片段快取:FragmentCache Widget 實現局部頁面快取
  • 客戶端腳本管理:JS/CSS 註冊與渲染
  • Asset Bundle:前端資源包管理
  • 模板引擎:支援 Twig、Smarty 等第三方引擎

SEO 與 Meta 標籤管理

// 頁面標題
$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/ 下的視圖檔案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved