主題化是一種替換一組視圖的方法,而無需接觸原始視圖渲染程式碼。您可以使用主題化來系統地更改應用程式的外觀和風格。
要使用主題化,您應該配置 view
應用程式組件的 theme 屬性。該屬性配置一個 yii\base\Theme 物件,該物件控制視圖檔案的替換方式。您應該主要指定 yii\base\Theme 的以下屬性
例如,如果您在 SiteController
中調用 $this->render('about')
,您將渲染視圖檔案 @app/views/site/about.php
。但是,如果您在以下應用程式配置中啟用主題化,則將渲染視圖檔案 @app/themes/basic/site/about.php
。
return [
'components' => [
'view' => [
'theme' => [
'basePath' => '@app/themes/basic',
'baseUrl' => '@web/themes/basic',
'pathMap' => [
'@app/views' => '@app/themes/basic',
],
],
],
],
];
資訊:主題支援路徑別名。在進行視圖替換時,路徑別名將轉換為實際的檔案路徑或 URL。
您可以通過 yii\base\View::$theme 屬性訪問 yii\base\Theme 物件。例如,在視圖檔案中,您可以編寫以下程式碼,因為 $this
指的是視圖物件
$theme = $this->theme;
// returns: $theme->baseUrl . '/img/logo.gif'
$url = $theme->getUrl('img/logo.gif');
// returns: $theme->basePath . '/img/logo.gif'
$file = $theme->getPath('img/logo.gif');
yii\base\Theme::$pathMap 屬性控制視圖檔案應如何替換。它接受鍵值對的陣列,其中鍵是要替換的原始視圖路徑,值是對應的主題視圖路徑。替換基於部分匹配:如果視圖路徑以 pathMap 陣列中的任何鍵開頭,則該匹配部分將替換為對應的陣列值。使用上面的配置範例,由於 @app/views/site/about.php
部分匹配鍵 @app/views
,因此它將替換為 @app/themes/basic/site/about.php
。
為了主題化模組,可以像下面這樣配置 yii\base\Theme::$pathMap
'pathMap' => [
'@app/views' => '@app/themes/basic',
'@app/modules' => '@app/themes/basic/modules', // <-- !!!
],
它將允許您將 @app/modules/blog/views/comment/index.php
主題化為 @app/themes/basic/modules/blog/views/comment/index.php
。
為了主題化小工具,您可以按以下方式配置 yii\base\Theme::$pathMap
'pathMap' => [
'@app/views' => '@app/themes/basic',
'@app/widgets' => '@app/themes/basic/widgets', // <-- !!!
],
這將允許您將 @app/widgets/currency/views/index.php
主題化為 @app/themes/basic/widgets/currency/views/index.php
。
有時您可能想要定義一個基本主題,其中包含應用程式的基本外觀和風格,然後根據當前節假日,您可能想要稍微改變外觀和風格。您可以使用主題繼承來實現此目標,主題繼承通過將單個視圖路徑映射到多個目標來完成。例如:
'pathMap' => [
'@app/views' => [
'@app/themes/christmas',
'@app/themes/basic',
],
]
在這種情況下,視圖 @app/views/site/index.php
將被主題化為 @app/themes/christmas/site/index.php
或 @app/themes/basic/site/index.php
,具體取決於哪個主題檔案存在。如果兩個主題檔案都存在,則第一個檔案優先。在實務中,您會將大多數主題視圖檔案保存在 @app/themes/basic
中,並在 @app/themes/christmas
中自訂其中一些檔案。
發現錯字或您認為此頁面需要改進嗎?
在 github 上編輯 !
註冊 或 登入 以發表評論。