Templates, which embed <%= ... %> or <% ... %> tags, are converted to executable Pnuts scripts. The code fragments in those tags may reference variables. Also code fragments may execute any script to generate dynamic contents.
This feature is a part of pnuts.servlet module. For details on the template file format, please consult 'Dynamic Pages' section.
When a DynamicPage object is created, the template specified by url is compiled. When DynamicPage.run(Context) method is called, expanded content is written to the Writer associated with the context. If checkUpdates is true (default), the last modified time of the template file is checked and if it has been updated since the template generated an output, it automatically re-compile the template.
import pnuts.lang.Pnuts;
import pnuts.lang.Context;
import pnuts.lang.Package;
import pnuts.lang.ParseException;
import pnuts.servlet.DynamicPage;
import java.net.*;
import java.util.*;
import java.io.*;
public class MyClass {
DynamicPage page;
Context context;
static Context setupContext(){
Context context = new Context();
context.usePackage("pnuts.servlet");
return context;
}
public MyClass(URL template, String encoding) throws IOException, ParseException {
this(template, encoding, setupContext());
}
public MyClass(URL template, String encoding, Context context)
throws IOException, ParseException
{
this.context = context;
this.page = new DynamicPage(template, encoding, context); // compiles the template
}
public void format(Map vars, Writer writer){
Package pkg = Package.wrap(vars);
Context context = (Context)this.context.clone();
context.setCurrentPackage(pkg);
context.setWriter(writer);
this.page.run(context);
}
public String format(Map vars){
StringWriter sw = new StringWriter();
format(vars, sw);
return sw.toString();
}
public static void main(String[] args) throws Exception {
MyClass instance = new MyClass(new File("template.txt").toURL(), "utf-8");
Map vars = new HashMap();
vars.put("properties", System.getProperties());
System.out.println(instance.format(map));
}
}
<%@escape%>
<table>
<% for (k, v : properties) { %>
<tr>
<td><%=k%></td>
<td><%=v%></td>
</tr>
<% } %>
</table>