[分享] 謹慎使用 Smarty 樣板的 {include} …

以下是在 PTT 的 PHP 板看到某篇文章後的心得,以及小小的經驗分享。

Smarty 稍有經驗的人,應該都知道樣板內可使用 {include} 這個 tag 來嵌入其他 template file。
然而,因為 Smarty 內的變數都是全域變數,所以我對這個 tag 的看法是「能不用,就不用」。

用常見的網站論壇系統舉個簡單的例子:

  • A 設計師負責開發顯示 HTML header 的 template,使用了 $title 變數作為 page title,ex:
    <html><head><title>$title</title></head>
  • B 設計師負責開發顯示論壇文章內容的 template,恰巧也使用了 $title 作為文章標題。

若 B 設計師在其 template file 中使用了 {include} 來嵌入 A 設計師的 template file,就可能會產生預期之外的顯示結果。

當然,若是開發團隊已事先溝通好各項變數的命名,就不會有這種情況。
但為了減少此類風險,降低 debug 的難度,我們會選擇使用這種方式:

  • 在系統全域共用的函式檔案中增加負責顯示 HTML header 的 function,例如 function page_header($title) { …} ,並在 function 中 assign 變數,引入 A 設計師開發的 template file。
  • 在論壇文章內容顯示的程式檔中,呼叫 page_header($title),再 assign 文章標題的變數,引入 B 設計師開發的 template file。

當然,若嵌入的 template file 內沒有任何變數,就不須考量以上的狀況,開發/設計人員可以大膽地隨意使用。 8-)