差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

Both sides previous revision 前次修改
下次修改
前次修改
java:mustache:helloworld [2016/08/27 22:30]
tony [第一個Template]
java:mustache:helloworld [2023/06/25 09:48] (目前版本)
行 1: 行 1:
 {{tag>​java mustache}} {{tag>​java mustache}}
-====== Mustache Hello World ======+====== Mustache ​Hello World ======
 ===== Introduction ===== ===== Introduction =====
 Mustache是Albert所找的template system engine。目的是為了讓你可以簡單的只使用資料物件(bean),用少少甚至無邏輯去定義輸出格式。如果想切換輸出格式,只要修改樣本檔案就好。 Mustache是Albert所找的template system engine。目的是為了讓你可以簡單的只使用資料物件(bean),用少少甚至無邏輯去定義輸出格式。如果想切換輸出格式,只要修改樣本檔案就好。
行 17: 行 17:
 </​code>​ </​code>​
 ==== 第一個Template ==== ==== 第一個Template ====
 +以下為我的測試資料物件:​
 +<code java>
 public class TestBean { public class TestBean {
  
行 25: 行 27:
  public String getPasswd(){  public String getPasswd(){
  return "​testPasswd";​  return "​testPasswd";​
 + }
 +
 + public boolean showPasswd(){
 + return false;
  }  }
 } }
 +</​code>​
 +以下為我的執行轉換程式,會去讀engine設定路徑下檔名為template1.txt的檔案,並將TestBean做轉換:​
 +<code java>
 +Mustache template = mustacheEngine.getMustache("​template1"​);​
 +System.out.println(template.render(new TestBean()));​
 +</​code>​
 +以下為我的範本,會顯示TestBean的name,並根據showPasswd決定顯示方式。#​代表存在或為true;^代表不存在或為false:​
 +<​code>​
 +name={{name}}
 +passwd={{#​showPasswd}}{{passwd}}{{/​showPasswd}}{{^showPasswd}}****{{/​showPasswd}}
 +</​code>​
 +==== Output ====
 +<​code>​
 +name=testName
 +passwd=****
 +</​code>​
 ===== Summary ===== ===== Summary =====
 如果把邏輯寫在程式中,資料物件就不是這麼單純的資料物件;如果把邏輯寫在樣本中,樣本就不是那麼容易維護。選擇透過程式或樣本決定輸出格式,就看你根據需求的取捨。 如果把邏輯寫在程式中,資料物件就不是這麼單純的資料物件;如果把邏輯寫在樣本中,樣本就不是那麼容易維護。選擇透過程式或樣本決定輸出格式,就看你根據需求的取捨。
- +===== 後記 ​===== 
-===== Reference ​===== +如果要選擇性顯示資料又不跳行,要寫成這樣: 
-  * [[https://en.wikipedia.org/wiki/Mustache_(template_system)|wiki - Mustache_(template_system)]] +<​code>​ 
-  * [[https://github.com/​spullara/​mustache.java|mustache.java]] +{{#​data1}} 
 +Data1:​{{data1}} 
 +{{/data1}} 
 +{{#​data2}} 
 +Data2:​{{data2}} 
 +{{/data2}} 
 +</code> 
 +如果寫成以下形式,且Data1不存在時,會多一空白行。 
 +<​code>​ 
 +{{#​data1}}Data1:​{{data1}}{{/data1}} 
 +{{#​data2}}Data2:{{data2}}{{/data2}} 
 +</code>
 =====  ===== =====  =====
 ---- ----