關於樣版的制定,FreeMarker提供了相當多的支援,如果已經熟悉JSP taglib, expression language (EL)的同學來學習 FreeMarker 樣版,會發現語法還蠻類似的,很容易就可以上手!以下提供幾個常用的特性,完整說明,可參考官方文件。
我們先修改一下範例程式
- 新增Book.java
12345678910111213package com.appx.demo.freemarker;public class Book {private String name;private String author;public Book(String name, String author) {this.name = name;this.author = author;}//getter, setter 請自行補上...} - 修改User.java
1234567891011121314151617181920212223242526package com.appx.demo.freemarker;import java.util.ArrayList;import java.util.Date;import java.util.List;public class User {private String name;private String location;private int cash;private Date createdDate;private List<Book> books = new ArrayList<>();public User(String name, String location, int cash, Date createdDate) {this.name = name;this.location = location;this.cash = cash;this.createdDate = createdDate;}public void addBook(Book book) {this.books.add(book);}// getter, setter 請自行補上...} - 稍微重構一下主程式App.java
12345678910111213141516171819202122232425262728293031323334package com.appx.demo.freemarker;import java.io.StringWriter;import java.util.Date;import freemarker.template.Configuration;public class App {public static void main(String[] args) throws Exception {//初始化freemarker設定Configuration cfg = new Configuration(Configuration.VERSION_2_3_26);//指定樣版所在位置 (這裡是classpath的templates資料夾底下)cfg.setClassForTemplateLoading(App.class, "/templates");cfg.setDefaultEncoding("UTF-8");//封裝資料的物件,可以是一般物件,也可以是List, Map 等集合物件User user = prepareData();//取得樣版處理後輸出到 StringWriterStringWriter sw = new StringWriter();cfg.getTemplate("helloworld.ftl").process(user, sw);//透過StringWriter的toString()取得內容,後續可以進行處理System.out.println(sw);}private static User prepareData() {User user = new User("Terry", "Taiwan", 201234, new Date());user.addBook(new Book("Java in Action", "Anderson"));user.addBook(new Book("Oracle tutorial", "Tom"));return user;}} - 修改helloworld.ftl,請留意Freemarker 註解 中各項說明
1234567891011121314151617181920212223242526272829303132<html><header></header><body><h1>Hello, ${name}!</h1><#-- 多層資料結構 -->The first book: ${books[0].name}<#-- 字串處理 -->User location: ${location?upper_case}<#-- 數字格式化 -->Cash: ${cash?string.currency}<#-- 日期格式化 -->Created Date: ${createdDate?string["yyyy-MM-dd"]}<#-- if else 邏輯處理 --><#if (cash > 100000)>Rich<#else>Make more money</#if><#-- for迴圈取出資料 --><#list books as book>${book?counter}: ${book.name}, written by ${book.author}</#list></body><#-- 匯入其它樣版內容 --><#include "footer.ftl"></html> - 新增 footer.ftl
1${.now?string["yyyy"]} Appx rocks! - 執行結果
1234567891011121314151617181920<html><header></header><body><h1>Hello, Terry!</h1>The first book: Java in ActionUser location: TAIWANCash: $201,234.00Created Date: 2017-05-11Rich1: Java in Action, written by Anderson2: Oracle tutorial, written by Tom</body>2017 Appx rocks!</html>
Facebook Comments