首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

FreeMarker 設計指南 (一):快速入門與核心概念

     編輯:Java 相關知識

核心公式

模板 + 資料模型 = 輸出

  • 設計師:專注呈現 (HTML/CSS/圖片),編寫模板。
  • 程式設計師:建立系統、準備動態資料 (資料庫/檔案/運算),組裝資料模型。
  • 模板中以 ${...} 標記動態資料位置,FreeMarker 合併輸出。

範例

<h1>Welcome ${user}!</h1>
<p>Our latest product: ${latestProduct.name}!</p>

資料模型 (樹狀結構):

(root)
|- user = "Big Joe"
|- latestProduct
   |- url = "products/greenmouse.html"
   |- name = "green mouse"

合併後輸出:

<h1>Welcome Big Joe!</h1>
<p>Our latest product: green mouse!</p>

資料模型結構

  • Hash (雜湊):類似目錄,含鍵值對,如 latestProduct。
  • Scalar (純量):類似檔案,單一值 (字串/數字),如 user、name。
  • Sequence (序列):有序列表,以索引存取,如 animals[0].name。

複雜模型範例

(root)
|- animals
   |- mouse
      |- size = "small"
      |- price = 50
   |- elephant
      |- size = "large"
      |- price = 5000
|- test = "It is a test"

模板三大元素

元素語法說明
插值${...}輸出變數值
FTL 標籤<#directive>控制邏輯 (if/list/include 等)
註解<#-- ... -->不輸出

常用指令範例

<!-- 條件判斷 -->
<#if animals.python.price < animals.elephant.price>
  Pythons are cheaper.
<#else>
  Pythons are not cheaper.
</#if>

<!-- 迴圈輸出表格 -->
<table>
  <tr><th>Name</th><th>Price</th></tr>
  <#list animals as being>
    <tr><td>${being.name}</td><td>${being.price} Euros</td></tr>
  </#list>
</table>

<!-- 包含外部檔案 -->
<#include "/copyright_footer.html">

<!-- 組合使用:大動物加粗 -->
<#list animals as being>
  <#if being.size = "large"><b>${being.name}</b><#else>${being.name}</#if>
  ${being.price} Euros
</#list>

中文編碼提示

若輸出中文亂碼,請在 Filter 中設定 response.setCharacterEncoding("UTF-8") 與 response.setContentType("text/html;charset=UTF-8")。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved