2011-06-02 43 views

回答

5

你可以給VelocityFreemarker一槍。我在電子郵件模板引擎中使用了這兩種方法。它們爲基本用例提供了簡單的語法,但稍後可能會變得非常複雜!

在這兩者中,我個人比較喜歡Freemarker,因爲他們提供了各種不同的內置函數,使格式化數字和文本變得非常簡單。

1

嘗試Apache的速度或FreeMarker的,也可以是有幫助的,對我來說,我使用的FreeMarker

0

同意,Apache的Velocity是一個良好的通話嵌入式情況。

如果你想要一個獨立的產品,你也可以使用Apache的Ant。它通過應用替代過濾器來減少副本任務中的模板。

10

StringTemplate是另一種選擇。 five-minute introduction給出了一些基本的例子和語法。

StringTemplate hello = new StringTemplate("Hello, $name$", 
              DefaultTemplateLexer.class); 
hello.setAttribute("name", "World"); 
System.out.println(hello.toString()); 
2

它很簡單,自己動手:

public class Substitution { 

    public static void main(String[] args) throws Exception { 
    String a = "[email protected]@ccc"; 

    // This can be easiliy FileReader or any Reader 
    Reader sr = new StringReader(a); 

    // This can be any Writer (ie FileWriter) 
    Writer wr = new StringWriter(); 

    for (;;) { 
     int c = sr.read(); 
     if (c == -1) { //EOF 
     break; 
     } 
     if (c == '@') { 
     String var = readVariable(sr); 
     String val = getValue(var); 
     wr.append(val); 
     } 
     else { 
     wr.write(c); 
     } 
    } 
    } 

    /** 
    * This finds the value from Map, or somewhere 
    */ 
    private static String getValue(String var) { 
    return null; 
    } 

    private static String readVariable(Reader sr)throws Exception { 
    StringBuilder nameSB = new StringBuilder(); 
    for (;;) { 
     int c = sr.read(); 
     if (c == -1) { 
     throw new IllegalStateException("premature EOF."); 
     } 
     if (c == '@') { 
     break; 
     } 
     nameSB.append((char)c); 
    } 
    return nameSB.toString(); 
    } 
} 

你要擦亮它一點點,但僅此而已。