🧩 什麼是 Twig?Drupal 的強大模板引擎介紹

2025-04-30

廣告

當你在用 Drupal 開發網站、客製化佈景主題時,一定會遇到 .html.twig 檔案。這不是普通的 HTML,而是 Drupal 內建使用的 Twig 模板引擎

本篇將帶你認識 Twig 是什麼、它的語法怎麼用、以及實務應用技巧。


✨ Twig 是什麼?

Twig 是一個現代化、快速且安全的 PHP 模板引擎,由 Symfony 專案開發,Drupal 8 起成為預設模板系統(取代 PHPTemplate)。

簡單來說,它讓前端開發者可以:

  • 更清楚地分離「邏輯」與「呈現」
  • 用簡潔安全的語法編寫樣板
  • 加入條件、迴圈、過濾器等動態邏輯

📁 Twig 檔案在哪裡?

Twig 檔案通常位於主題中的:

/themes/custom/你的主題/templates/

常見檔名:

  • node.html.twig:節點內容
  • page.html.twig:整個頁面結構
  • block.html.twig:區塊區域
  • field--field_XXX.html.twig:單一欄位
  • views-view-unformatted.html.twig:Views 輸出樣板

🛠️ 基本語法速查

變數輸出

{{ title }}
{{ content.body }}

條件判斷

{% if logged_in %}
  <p>歡迎回來,{{ user.name }}</p>
{% else %}
  <p>請先登入。</p>
{% endif %}

迴圈

<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

過濾器(Filters)

{{ title|striptags|length }}
{{ node.created|date("Y-m-d") }}

🎯 Twig 在 Drupal 裡的應用

1. 客製化內容顯示格式

你可以透過 field--field_image.html.twig 改變圖片欄位的輸出 HTML:

<img src="{{ item.content['#item'].entity.uri.value }}" alt="{{ item.content['#item'].alt }}" />

2. Views 自定義輸出

自定義 Views 樣板:

views-view-fields--YOUR-VIEW-ID--YOUR-DISPLAY-ID.html.twig

可自訂每個欄位怎麼顯示、加上排版、icon、連結等。

3. 增強 SEO 與語意標記

page.html.twig 中加入 schema 標記:

<article itemscope itemtype="https://schema.org/Article">
  <h1 itemprop="headline">{{ title }}</h1>
  <div itemprop="articleBody">{{ content }}</div>
</article>

🔧 如何開啟 Twig debug 模式?

若你想知道某頁是由哪個 Twig 檔案渲染的,可以在 services.yml 啟用 debug:

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

重新清除快取後 (drush cr),檢查網頁原始碼就能看到:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'node' -->
<!-- FILE NAME SUGGESTIONS: -->
<!-- node--article.html.twig -->
<!-- node.html.twig -->

💡 Twig 實用技巧

功能 語法範例
加入 class <div class="box {{ custom_class }}">
檢查值存在 {% if variable is defined %}
安全過濾 HTML {{ content|raw }}
取得路由連結 {{ path('entity.node.canonical', {'node': node.id}) }}

✅ 總結

Twig 是 Drupal 強大的模板語言,結構清晰、安全性高,是前後端分工的利器。無論你是要製作設計精緻的網站、客製欄位樣式,還是整合 SEO 架構,都離不開 Twig。


廣告