ScarShow

< IS >

關於 PHP 原生樣板引擎

2013-04-04  /  IT  /  PHP

前言

想寫一個簡單的網頁程式,但現在市面上PHP的樣板引擎百百種,那該選什麼樣的樣板引擎來搭配好呢?...等等先不說這個,你有聽說過PHP本身也是樣板引擎嗎?沒錯它是。

在這之前我們先看看Wikipedia是怎麼解釋樣板引擎:

"A (web) template engine is software that is designed to process web templates and content information to produce output web documents. It runs in the context of a template system."

它說明了樣板引擎的功能是將內容資訊與網頁樣板結合,然後產生出網頁文件的這一個行為。將網頁的內容與網頁樣板切開,這個不用幾行程式碼PHP就可以做到。

替換語法

不用其他樣板引擎那樣炫目的結構語法,PHP就有內建控制結構的替換語法,PHP官方手冊這邊就有寫了 Alternative syntax for control structures ,PHP內建的替換語法包含if, while, for, foreach以及switch這些耳熟能詳的語法,我們可以這樣去使用它:

<?php if($scores >= 60): ?>
<span>Congratulation!</span>
<?php endif; ?>

<ol>
    <?php foreach($list as $name): ?>
    <li><?=$name?></li>
    <?php endforeach; ?>
</ol>

上面示範了if():以及foreach():的語法,它基本使用上就跟我們在PHP中的寫法差不多,每個語法都必須在<?php ?>的標籤中,不過稍有不同的是語法後面都要加上:以及在區塊的最後加上<?php endxxx; ?>結束語法來作結尾。然而變數的輸出可以使用一般的<?php echo $variable; ?>,也可以使用在PHP中稱為Short Tag的特殊標籤<?=$variable?>,如果你的PHPPHP 5.4之前的版本,請修改php.iniShort Tag的支援打開。

short_open_tag = On

在這邊我們要注意的是,PHP只做邏輯判斷並且印出事先就處理好的變數內容,並且盡量少用PHP印出HTML的標籤,這樣做的話會讓樣板更乾淨。

資料處理與讀取樣板

讓資料與樣板切割最快也最徹底的方式就是分檔,但是分檔完之後還是要將樣板與資料做結合,所以動手做一個render來將樣板跟資料做結合吧!

<?php
function render($template, $data) {
    ob_start();
    include $template;
    $result = ob_get_contents();
    ob_end_clean();

    return $result;
}

這個render函式是利用output buffer來取得資料與樣板結合後的HTML文件,並且將HTML回傳。

使用範例

我們這邊假設寫一個呈現學生清單的網頁,並且分為兩個網頁一個是處理資料student_info.php還有它所讀取的網頁樣板list_template.php

student_info.php

<?php
// query database

$info = array(
    array('id' => 1, 'name' => 'Tony'),
    array('id' => 2, 'name' => 'Micky'),
    array( ... )
);

$html = render('list_template.php', $info);
echo $html;

list_template.php

<html>
    <head>
        <title>Student List</title>
    </head>
    <body>
        <table>
            <tr>
                <td>ID</td><td>Name</td>
            </tr>
            <?php foreach($data as $student): ?>
            <tr>
                <td><?=$student['id']?></td><td><?=$student['name']?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </body>
</html>

輸出結果

<html>
    <head>
        <title>Student List</title>
    </head>
    <body>
        <table>
            <tr>
                <td>ID</td><td>Name</td>
            </tr>
            <tr>
                <td>1</td><td>Tony</td>
            </tr>
            <tr>
                <td>2</td><td>Micky</td>
            </tr>
            <tr>
                <td>3</td><td> ... </td>
            </tr>

            ...

        </table>
    </body>
</html>

就這樣沒了。

不負責結論

當然現成的樣板引擎當然有它的好處,但如果你想要附屬的好用功能當然還是可以用,比較起那些炫目簡短的語法,但我還是會選擇原生的語法(雖然醜了點),廣告台詞說了這麼一句:天然ㄟ尚好,畢竟人家都已經做好放在那邊而且速度又比較快,也沒有什麼理由不用,如果要簡單的附加功能大不了自己寫也是可以的。

我還是強調一下,要不要用樣板引擎,這全憑個人選擇。

Update: 2014/05/08