:::
5-1 建立主樣板檔 index.tpl 並套用之
- 我們可以先將原本的
index.html,另存為templates/index.tpl(或將index.html拖到templates下,按 F2 修改副檔名),作為主要樣板檔 - 利用樣板引擎的
display()方法就可以套用樣板檔(無須指定templates目錄)。 - 編輯
index.php,將直接echo的部份都註解掉 - 在最後一行加入欲套用
index.tpl樣板的語法:<?php require_once 'header.php'; try { // 準備SQL語句 $sql = "SELECT * FROM news ORDER BY date DESC"; // 預備語句 $stmt = $pdo->prepare($sql); // 綁定參數並執行語句 $stmt->execute(); $news = $stmt->fetchAll(); foreach ($news as $row) { // 在這裡處理每一筆資料 $row = array_map('htmlspecialchars', $row); // echo "<li>{$row['title']}</li>"; } } catch (PDOException $e) { echo "資料庫連接錯誤:" . $e->getMessage(); } $smarty->display('index.tpl'); - 如此,執行 http://localhost/index.php 便可看到套用後結果囉!
- 順利的話,應該和直接觀看 http://localhost/index.html 一模一樣才是。

- 不過,目前PHP和樣板並沒有真的結合起來!!我們只是確認了Smarty有在運行而已,顯示的內容依舊是之前寫死的。
5. 用Smarty樣板引擎將資料與前端結合