這是本文件的舊版!
Mustache Hello World
Introduction
Mustache是Albert所找的template system engine。目的是為了讓你可以簡單的只使用資料物件(bean),用少少甚至無邏輯去定義輸出格式。如果想切換輸出格式,只要修改樣本檔案就好。
How to?
Create Engine
使用Mustache的第一步就是要建立它的Engine instance,而方法就是透過MustacheEngineBuilder。以我的例子來說,我告訴了builder樣本的放置位置,第一優先從classpath中的templates資料夾中找尋txt結尾之檔案,第二優先為工作目錄的templates中找尋txt結尾之檔案:
TemplateLocator locator1 = new ClassPathTemplateLocator(1, "templates","txt"); TemplateLocator locator2 = new FileSystemTemplateLocator(2, Paths.get("templates").toString(), "txt"); MustacheEngine mustacheEngine = MustacheEngineBuilder .newBuilder() .addTemplateLocator(locator1) .addTemplateLocator(locator2) .build();
第一個Template
public class TestBean { public String getName(){ return "testName"; } public String getPasswd(){ return "testPasswd"; } public boolean showPasswd(){ return false; } }
name={{name}} passwd={{#showPasswd}}{{passwd}}{{/showPasswd}}{{^showPasswd}}****{{/showPasswd}}
Mustache template = mustacheEngine.getMustache("template1"); System.out.println(template.render(new TestBean()));
Summary
如果把邏輯寫在程式中,資料物件就不是這麼單純的資料物件;如果把邏輯寫在樣本中,樣本就不是那麼容易維護。選擇透過程式或樣本決定輸出格式,就看你根據需求的取捨。
Reference