透過 partial 重新使用視圖(Reusing views via partials)

一個開發很重要的原則是「不要自我重複」(don't repeat yourself,DRY)。 重複的程式碼在開發期間到處都會出現,包括視圖的部份,這邊我們建立一些可重複使用的視圖,來解決這問題。

1. 建立 partial view

下面是常見的views/site/index.php程式碼:

<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<div class="site-index">
<div class="jumbotron">
    <h1>Congratulations!</h1>
    <p class="lead">You have successfully created your Yii-powered application.</p>
    <p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<div class="body-content">
//...

舉例來說,我們希望<div class="jumbotron">HTML 區塊的部份,可以同時出現在首頁與「關於我們」views/site/about.php裡面。並且這段區塊不要自我重複。

我們來建立獨立的視圖檔views/site/_jumbotron.php,並把下面的HTML放進來:

<div class="jumbotron">
    <h1>Congratulations!</h1>
    <p class="lead">You have successfully created your Yii-powered application.</p>
    <p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>

2. 使用 partial view

將原本views/site/index.php內,<div class="jumbotron">HTML 區塊的東西,改成如下:

<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<div class="site-index">
<?=$this->render('_jumbotron.php')?>; // 取代原本的 jumbotron 區塊
<div class="body-content">
//...

在「關於我們」views/site/about.php裡面,加入一樣的程式碼(也可以加在其他的視圖內):

<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
$this->title = 'About';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
    <?=$this->render('_jumbotron.php')?>; // 取代原本的 jumbotron 區塊

上面的程式碼內,我們靠View::render()函式處理指定的視圖,並回傳HTML格式的輸出,讓我們可以送出至使用者。

3. 加入變數

再來,我們讓 jumbotron 裡面的訊息也可以改變。原本的視圖裡面訊息是固定的,要能改變,我們透過加入一個message參數,並且依照需求傳入不同資料。

首先, 我們自製的views/site/_jumbotron.php,改成:

<?php
$message = isset($message) ? $message : 'You have successfully created your Yii-powered application.';
?>
<div class="jumbotron">
    <h1>Congratulations!</h1>
    <p class="lead"><?= $message ?></p>
    <p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>

然後在「關於我們」裡面,傳入message參數:

<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
$this->title = 'About';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
    <?=$this->render('_jumbotron.php', [
        'message' => 'This is about page!',
    ])?>; // 我們的程式碼

results matching ""

    No results matching ""