User Guide
Invoking templates from Java
- First, make sure you have preprocessed the top-level templates into their Java equivalents.
- When building your project, be sure to include the generated source files in the build process.
- Optional Create a TemplateManager instance (e.g. the RecompilingTemplateManager), and configure it appropriately
- Create an instance of the template, set any optional arguments, and invoke its render method.
Example
Suppose the template intemplates/org/foo/templates/Foo contains
<%args>
int count;
String name = "Somebody";
String greeting;
</%args>
<html>
<body>
<%for int i = 1; i <= count; ++i %>
<% i %>. <% greeting %> <% name %> <br />
</%for>
</body>
</html>
This can be processed into a Java interface with the
Jamon TemplateProcessor class, e.g.
java org.jamon.TemplateProcessor --destDir=./gensrc --srcDir=templates templates/org/foo/templates/Foowhich will place the generated Java source file(s) into the
gensrc directory.
You can then use the template as follows:
import org.foo.templates.Foo;
import org.jamon.RecompilingTemplateManager;
import org.jamon.TemplateManager;
import org.jamon.TemplateManagerSource;
...
TemplateManager manager = new RecompilingTemplateManager(...);
TemplateManagerSource.setTemplateManager(manager);
Writer writer = new OutputStreamWriter(System.out);
Foo foo = new Foo();
foo.setName("Duke & Co.");
foo.render(writer, 3, "Hello");
// alternatively:
foo = new Foo();
foo.setName("Duke & Co.");
org.jamon.Renderer r = foo.makeRenderer(3, "Hello");
r.renderTo(writer);
// or even:
foo = new Foo();
foo.setName("Duke & Co.");
String value = foo.makeRenderer(3, "Hello").asString();
writer.write(value);
When you build your project, be sure to include the java files
in the gensrc directory in the compilation command.
Execution of the above code snippet produces the output
<html>
<body>
1. Hello Duke & Co.<br />
2. Hello Duke & Co.<br />
3. Hello Duke & Co.<br />
</body>
</html>
Changing the default escaping mechanism
Suppose the we wanted to include some text for inclusion in an email. Since we are producing plain text (and not HTML) we want a different default escaping mechanism. This can be specified in the template as follows:
<%escape #n>
<%args>
int count;
String name = "Somebody";
String greeting;
</%args>
Many Greetings
==============
<%for int i = 1; i <= count; ++i %>
<% i %>. <% greeting %> <% name %>
</%for>
It would emit
Many Greetings
==============
1. Hello Duke & Co.
2. Hello Duke & Co.
3. Hello Duke & Co.
The available escaping mechanisms are:
Escaping.NONE(#n)Escaping.HTML(#h)Escaping.STRICT_HTML(#H)Escaping.URL(#u)Escaping.XML(#x)