:::

5-1 建立主樣板檔 index.tpl 並套用之

  1. 我們可以先將原本的 index.html,另存為 templates/index.tpl(或將 index.html 拖到 templates 下,按 F2 修改副檔名),作為主要樣板檔
  2. 利用樣板引擎的 display() 方法就可以套用樣板檔(無須指定 templates 目錄)。
  3. 編輯 index.php,將直接 echo 的部份都註解掉
  4. 在最後一行加入欲套用 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');
    

     

  5. 如此,執行 http://localhost/index.php  便可看到套用後結果囉!
  6. 順利的話,應該和直接觀看 http://localhost/index.html 一模一樣才是。
  7. 不過,目前PHP和樣板並沒有真的結合起來!!我們只是確認了Smarty有在運行而已,顯示的內容依舊是之前寫死的。

 

 


:::

書籍目錄

展開 | 闔起

https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D52%26tbdsn%3D1804

計數器

今天: 1729172917291729
昨天: 3438343834383438
總計: 7392058739205873920587392058739205873920587392058