本系列最終篇,涵蓋 Twig 安全輸出控制(autoescape、raw)、串流輸出(flush)、表達式執行(do)等特殊標籤,並附上完整過濾器與函數快速參考表。
Twig 預設啟用自動轉義(HTML 語境),將 & < > ' " 轉為實體。autoescape 標籤可區域性控制策略。
{% autoescape true %} {# 啟用 HTML 轉義(預設) #}
{% autoescape false %} {# 關閉自動轉義 #}
{% autoescape 'js' %} {# JavaScript 語境轉義 #}
{% autoescape 'css' %} {# CSS 語境轉義 #}
{% autoescape 'url' %} {# URL 語境轉義 #}
{% endautoescape %}
{% autoescape true %}
{{ variable }} {# 會被 HTML 轉義 #}
{{ safe_html|raw }} {# raw 標記跳過轉義 #}
{% endautoescape %}
{% autoescape 'js' %}
var msg = "{{ user_input }}"; {# 會轉義為 JS 字串安全格式 #}
{% endautoescape %}
parent()、block()、macro 呼叫)標記為「安全」,不會被再次轉義autoescape 僅影響區塊內直接輸出 的變數html(預設)、js、css、url、html_attr標記區塊內容為「已安全」,完全跳過模板引擎解析與轉義。
{% raw %}
<ul>
{% for item in seq %}
<li>{{ item }}</li> {# 這裡的 {{ }} 會原樣輸出,不被解析 #}
{% endfor %}
</ul>
{% endraw %}
常用於:展示程式碼片段、輸出包含 Twig 語法的文字、前端模板(Vue/React)共存頁面。
Twig 1.5+ 新增。呼叫 PHP flush() 將輸出緩衝區送至瀏覽器,適用於長時間執行的頁面漸進式渲染。
<html>
<head><title>Large Page</title></head>
<body>
{% include 'header.twig' %}
{% flush %} {# 先送出 header,使用者較快看到內容 #}
{% for item in large_dataset %}
{{ item.render() }}
{% endfor %}
{% include 'footer.twig' %}
</body>
</html>
Twig 1.5+ 新增。類似 {{ ... }} 但不輸出結果,用於執行有副作用的表達式(如陣列操作、設定變數、呼叫無回傳值方法)。
{% do navigation.addItem('Home', '/') %}
{% do form.setErrors(errors) %}
{% do 1 + 2 %} {# 無意義但合法 #}
| 過濾器 | 功能 | 範例 |
|---|---|---|
date | 格式化日期 | {{ post.published_at|date("Y-m-d") }} |
format | sprintf 風格格式化 | {{ "I like %s"|format(foo) }} |
replace | 字串替換 | {{ "a,b"|replace({',': ';'}) }} |
number_format | 數字格式化 | {{ 1234.5|number_format(2, '.', ',') }} |
url_encode | URL 編碼 | {{ data|url_encode }} |
json_encode | JSON 編碼 | {{ data|json_encode }} |
convert_encoding | 編碼轉換 | {{ data|convert_encoding('UTF-8', 'ISO-2022-JP') }} |
title | 每單字首字大寫 | {{ 'my car'|title }} → My Car |
capitalize | 首字大寫其餘小寫 | {{ 'MY CAR'|capitalize }} → My car |
nl2br | 換行轉 <br> | {{ text|nl2br }} |
upper/lower | 大/小寫轉換 | {{ name|upper }} |
striptags | 移除 HTML 標籤 | {{ html|striptags }} |
join | 陣列串接 | {{ [1,2,3]|join('|') }} → 1|2|3 |
reverse | 反轉陣列/可迭代物件 | {% for u in users|reverse %} |
length | 陣列/字串長度 | {% if users|length > 10 %} |
sort | 排序陣列 | {% for u in users|sort %} |
default | 預設值 | {{ var|default('N/A') }} |
keys | 取得陣列鍵名 | {% for k in arr|keys %} |
escape/e | HTML 轉義 | {{ name|e }}、{{ name|escape('js') }} |
raw | 標記為安全 | {{ safe|raw }} |
merge | 合併陣列/關聯陣列 | {{ {'a':1}|merge({'b':2}) }} |
| 函數 | 功能 | 範例 |
|---|---|---|
attribute | 動態存取屬性/方法 | {{ attribute(obj, method, args) }} |
block | 輸出區塊內容 | {{ block('title') }} |
constant | 讀取常數 | {{ constant('DATE_W3C') }} |
cycle | 循環取值 | {{ cycle(['odd','even'], i) }} |
dump | 除錯輸出 (需 Debug 擴充) | {{ dump(var) }}、{{ dump() }} |
parent | 父區塊內容 | {{ parent() }} |
random | 隨機取值 | {{ random(['a','b','c']) }} |
range | 產生數字範圍陣列 | {{ range(0, 3) }} → [0,1,2,3] |
|rawinclude 造成碎片化new Twig\Environment($loader, ['cache' => '/path/to/cache'])['strict_variables' => true] 開發期捕獲拼字錯誤['auto_reload' => true] 開發期自動偵測模板變更三篇文章完整涵蓋 Twig 所有核心標籤:
for、if、macro、import/from、filterset、extends/block、include、use、spacelessautoescape、raw、flush、do、完整過濾器/函數參考掌握這些功能,即可充分發揮 Twig 的表達力與安全性,構建可維護、高效能的現代 PHP 應用視圖層。