Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2005

Tip: Looking for answers? Try searching our database.

ANN. SimpleTemplate - Template Engine for java

Thread view: 
frankgerlach22@gmx.de - 02 Aug 2005 15:00 GMT
SimpleTemplate is a simple, but powerful template engine for java. It
is
similar to PHP template engines. SimpleTemplate can be used to generate
any text, eg. HTML, ASCII flat file or java source code. The engine can
be
used as a libary for any java program, not just servlet containers.
Size is just 23 kilobytes.

Example Template file:
<html>
<body>
Hello {VAR Customer}. Welcome to Acme Banking.
Your account balance is {VAR Balance}.
</body>
</html>

java code:
engine.useTemplate("Bank.tpl");
engine.setVariable("Customer","Donald Duck");
engine.setVariable("Balance","1000.000.000");
StringBuffer outb=engine.createOutput();
FileWriter fw=new FileWriter("./output/Bank.html");
fw.write(outb.toString());
fw.close();

It is obvious that a template files are simpler to maintain than JSP
if an application grows to medium or large size.
*******************************************************
Download from http://fgerlach.com/SimpleTemplate.tar.gz
*******************************************************
Harald - 02 Aug 2005 20:20 GMT
> java code:
> engine.useTemplate("Bank.tpl");
[quoted text clipped - 4 lines]
> fw.write(outb.toString());
> fw.close();

May I suggest to think about the interface again? Obviously there is a
method

 StringBuffer createOutput();

I see two drawbacks and then will propose an alternative:

a) The StringBuffer object has to be created for each invocation.
b) The result as a whole has to be assembled completely in memory
before anything can be done with it.

Instead let me suggest the interface

 void createOutput(StringBuffer out);
 void createOutput(PrinteWriter out);

or even, if you are using 1.5

 void createOutput(Appendable out);

which easily combines the two above. In particular the last version
gives the user the greatest freedom of where to drain the generated
data. In addition it relieves you from allocating a StringBuffer for
each invocation.

Another ideas, but slightly more complicated: make your engine
InputReader, i.e. the user can even decide how much data (s)he wants
to have on each invocation.

 Harald.

Signature

---------------------+---------------------------------------------
Harald Kirsch (@home)|
Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

frankgerlach22@gmx.de - 02 Aug 2005 21:35 GMT
There are multiple objects created by SimpleTemplate at runtime, so it
should not matter too much that a StringBuffer is created. But you are
right that an output stream would be a good idea..
Bryce - 02 Aug 2005 21:00 GMT
>SimpleTemplate is a simple, but powerful template engine for java. It
>is
[quoted text clipped - 3 lines]
>used as a libary for any java program, not just servlet containers.
>Size is just 23 kilobytes.

How's this different from Velocity:
http://jakarta.apache.org/velocity/index.html

--
now with more cowbell
frankgerlach22@gmx.de - 02 Aug 2005 21:32 GMT
Bryce schrieb:

> How's this different from Velocity:
> http://jakarta.apache.org/velocity/index.html
BIG difference: Velocity provides plenty of features which are IMO
redundant: IF, FOR etc. SimpleTemplate just allows you to structure
the template as a tree of Sections. Java code will then (separate
from the template) instantiate these Sections zero, one or more
times. No need for loops or conditionals, as Java already provides
that semantic. Velocity is ten to 100 times larger than SimpleTemplate.
Stefan Ram - 03 Aug 2005 01:39 GMT
>SimpleTemplate is a simple, but powerful template engine for java. (...)
>Hello {VAR Customer}. Welcome to Acme Banking.
>Your account balance is {VAR Balance}.

 Software for such a purpose must have be around since a time
 long before Java appeared. But I believe that "template
 engine" is a new term appearing later. How was it called
 before? Or is a "template engine" really such a recent
 invention?

 Which features must a library offer to be called a "template
 engine"?

<html>Hello {VAR Customer}. Welcome to Acme Banking.
Your account balance is {VAR Balance}. </html>
engine.useTemplate("Bank.tpl");
engine.setVariable("Customer","Donald Duck");
engine.setVariable("Balance","1000.000.000");

 In Java, something similar might also be written as follows.

class Main
{ public static void main( final String[] _ )
 { java.lang.System.out.println
   ( ( "<html>Hello {VAR Customer}. Welcome to Acme Banking.\n" +
       "Your account balance is {VAR Balance}.</body>\n" ).
     replace( "{VAR Customer}", "Donald Duck" ).
     replace( "{VAR Balance}", "1000.000.000" )); }}
frankgerlach22@gmx.de - 03 Aug 2005 18:54 GMT
Ok, I need to present a more complex example
to show why SimpleTemplate is a useful tool,
which cannot be emulated by string replacement:
-------------------------
First, the template file:

<html>
<body>
Hello {VAR CustomerName}
This is your account statement:
<table border="1">
 <tr><td>Reason for payment</td><td>Amount</td></tr>
 {BEGIN StmtRow}
 <tr><td>{VAR Reason}</td><td>{VAR Amount}</td></tr>
 {END StmtRow}
</table>
Your new balance is {VAR Balance}
</body>
</html>
--------------------------------------------
Now the java code operating on the template:

import org.fg.SimpleTemplate.*;
import java.io.*;

public class Statement{

public static void main(String[] argv){
  try{
    //set the prefix for template files -
    //ADAPT THIS TO YOUR SETUP
    TemplateEngine.stFilenamePrefix=
      "c:/franksordner/dev/SimpleTemplate/examples/";
    TemplateEngine engine=new TemplateEngine();

    String[] reasons={"Creditcard","Gas","Electricity",
                    "Water"};
    engine.useTemplate("Statement.tpl");
    engine.setVariable("CustomerName","Dagobert Duck");
    for(int i=0;i<reasons.length;i++)
    {
      engine.beginSection("StmtRow");
        //note: in a real application, the following
        //data would likely come from an SQL
        //result set
        engine.setVariable("Reason",reasons[i]);
        engine.setVariable("Amount","-"+(i+100.15));
      engine.endSection("StmtRow");
    }
    engine.setVariable("Balance","+199.66");

    StringBuffer outb=engine.createOutput();
    FileWriter fw=new FileWriter("./output/Statement.html");
    fw.write(outb.toString());
    fw.close();
  }catch(Exception e){
      System.out.println("caught exception:"+e);
  }
}//end main()
}//end class
------------------------
and finally, the output:

<html>
<body>
Hello Dagobert Duck
This is your account statement:
<table border="1">
 <tr><td>Reason for payment</td><td>Amount</td></tr>

 <tr><td>Creditcard</td><td>-100.15</td></tr>

 <tr><td>Gas</td><td>-101.15</td></tr>

 <tr><td>Electricity</td><td>-102.15</td></tr>

 <tr><td>Water</td><td>-103.15</td></tr>

</table>
Your new balance is +199.66
</body>
</html>
-------------------------------------------------------
How would you do this with simple String replacement ?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.