🛠️ Drupal 自訂 Custom Twig Formatter 教學
2025-04-30
標籤: 模組
廣告
打造屬於你的欄位輸出樣板
在開發 Drupal 網站時,你可能會遇到這樣的需求:
- 想讓某個欄位的輸出樣式更自由
- 想避免寫複雜的
hook_preprocess_field()
- 想直接在
.twig
檔案中自訂 HTML 結構
這時你可以使用 Custom Twig Field Formatter 模組,讓你輕鬆用 Twig 建立自訂欄位顯示格式(formatter),比 Views template 更彈性!
🔧 什麼是 Custom Twig Formatter?
Custom Twig Field Formatter 模組 允許你用 Twig 模板來建立欄位的 顯示格式器(Field Formatter)。
一句話說明:
「它讓你可以為每個欄位定義自己的
formatter
,並直接使用 Twig 決定欄位要怎麼輸出。」
📦 安裝模組
composer require drupal/custom_twig_formatter
drush en custom_twig_formatter
🪄 使用方式概覽
步驟一:建立顯示格式
-
到 管理 > 結構 > Twig Formatters
/admin/structure/twig_formatter
-
點選「新增 Twig Formatter」
-
設定內容:
- Label:格式名稱(會顯示在欄位管理介面)
- Machine name:系統名稱
- 實體類型:選擇
node
或其他 - Bundle:例如
article
- 欄位名稱:選一個你要客製的欄位
- 顯示模式:
default
或teaser
- Twig 模板內容:你可以輸入自訂 HTML + Twig
範例一:自訂文字欄位的樣式
<div class="custom-title">
<strong>{{ item.value }}</strong>
</div>
範例二:處理多個項目(如多張圖片)
<div class="image-gallery">
{% for item in items %}
<img src="{{ item['#item'].entity.uri.value | file_url }}" alt="{{ item['#item'].alt }}">
{% endfor %}
</div>
💡 可用變數
變數 | 說明 |
---|---|
item |
當只有一筆資料時使用 |
items |
多筆資料使用迴圈 |
element |
整個欄位物件 |
entity |
節點物件,可取用其他欄位 |
view_mode |
顯示模式,如 default 、teaser |
🧠 進階應用
取得其他欄位值
<h2>{{ entity.field_subtitle.value }}</h2>
<p>{{ item.value }}</p>
加上 Schema 標記
<div itemscope itemtype="https://schema.org/Organization">
<span itemprop="name">{{ item.value }}</span>
</div>
✅ 優點總結
- 不需寫 PHP 也能客製輸出樣式
- 支援欄位層級控制,不影響全站
- 可以輸出乾淨、語意清楚的 HTML
- 搭配 Views、Block 使用效果更強大
📌 建議搭配模組
模組名稱 | 用途 |
---|---|
Twig Tweak |
在 Twig 模板中呼叫 entity/view block 等功能 |
Field Group |
管理欄位群組與欄位呈現結構 |
Display Suite |
搭配自訂欄位排版結構使用 |