FreeMarker 是**伺服器端模板引擎**,核心價值:**將「資料模型」與「展示邏輯」分離**,輸出任意文字格式(HTML、XML、JSON、SQL、代碼、郵件、配置檔)。
| 硬編碼輸出 | FreeMarker 模板 |
|---|---|
| 邏輯與展示耦合,修改格式需改代碼重編譯 | 模板外置,熱加載,業務/前端可獨立維護 |
| 複雜迴圈/條件/格式化代碼冗長難讀 | 模板語法簡潔(`${var}`、`<#list>`、`<#if>`) |
| 難以支援多輸出格式(HTML/文本/代碼) | 同一資料模型,多模板輸出不同格式 |
| 無宏/繼承/包含機制,重用差 | 支援 `<#macro>`、`<#include>`、`<#extends>` 結構化重用 |
// Java
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
Template tpl = cfg.getTemplate("welcome.ftl");
Map model = Map.of("user", "Alice", "items", List.of("Apple", "Book"));
try (Writer out = new FileWriter("welcome.html")) {
tpl.process(model, out);
}
Welcome, ${user}!
<#list items as item>
- ${item}
#list>
輸出 `welcome.html` 即為渲染結果。**模板即文檔,文檔即模板**,所見即所得。
結論:FreeMarker 不是「輸出到控制台/檔案的工具」,而是**「文字結構化生成的標準化引擎」**,凡是「固定骨架 + 變動資料」的文字產出場景皆適用。