在 Symfony 專案中,Twig 是預設模板引擎。掌握三種基本語法即可應付大多數場景:
| 語法 | 用途 | 範例 |
|---|---|---|
{{ ... }} | 輸出變數/運算式結果 | {{ user.name }} |
{% ... %} | 控制結構(判斷、迴圈、區塊) | {% if user.isActive %}...{% endif %} |
{# ... #} | 註解(不會輸出至 HTML) | {# 這是註解 #} |
{# 判斷布林值 #}
{% if online == false %}
<p>網站維護中,請稍後再來。</p>
{% endif %}
{# 判斷陣列非空並迴圈 #}
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
{# 判斷變數是否定義 #}
{% if users is defined %}
<li>{{ user.username|e }}</li>
{% endif %}
Symfony 自動注入一個 app 全域變數,封裝常用服務:
app.session — Session 物件app.request — Request 物件app.user — 當前登入使用者app.environment — 當前環境app.debug — 是否除錯模式{# 取得 session 中的 'varname' 值 #}
{{ app.session.get('varname') }}
{# 判斷 session 是否存在某鍵值 #}
{% if app.session.has('flash_message') %}
<div class="alert">{{ app.session.get('flash_message') }}</div>
{% endif %}
{# 取得查詢字串參數 ?page=2 #}
{{ app.request.query.get('page') }}
{# 取得 POST 表單欄位 #}
{{ app.request.request.get('username') }}
{# 取得路由參數(如 /user/{id}) #}
{{ app.request.attributes.get('id') }}
{# 取得完整 URL #}
{{ app.request.uri }}
{# 當前使用者物件 #}
{{ app.user.username }}
{{ app.user.email }}
{# 環境判斷 #}
{% if app.environment == 'prod' %}
<script src="analytics.js"></script>
{% endif %}
{# CSRF Token(表單保護) #}
{{ csrf_token('form_intention') }}
若需在所有模板共享自訂資料,可在 twig.yaml 或透過 TwigExtension 註冊:
# config/packages/twig.yaml
twig:
globals:
site_name: "我的網站"
ga_tracking_id: "UA-XXXXXXXX-X"
模板中直接使用:{{ site_name }}
app.session 是陣列:實為 SessionInterface 物件,需呼叫 get()、has() 等方法|e 過濾器防止 XSS,或啟用 autoescape