| Template code | Output |
|---|---|
<table>
<%
var aList = [
{ month: "January", dayCount: 31 },
{ month: "February", dayCount: 28 },
{ month: "March", dayCount: 31 }
];
for (var i = 0; i < aList.length; i++) {
%>
<tr>
<td><%= aList[i].month %></td>
<td><%= aList[i].dayCount %></td>
</tr>
<%
}
%>
</table>
|
<table>
<tr>
<td>January</td>
<td>31</td>
</tr>
<tr>
<td>February</td>
<td>28</td>
</tr>
<tr>
<td>March</td>
<td>31</td>
</tr>
</table>
|
| Template code | Output |
|---|---|
ID,First name,Last name<%
var aList = [
{ id: 1, firstName: "Sharon", lastName: "Sharalike"},
{ id: 2, firstName: "Justin", lastName: "Case"},
{ id: 3, firstName: "Eileen", lastName: "Dover"}
];
for (var i = 0; i < aList.length; i++) {
%>
${aList[i].id},${aList[i].firstName},${aList[i].lastName}<% } %>
|
ID,First name,Last name
1,Sharon,Sharalike
2,Justin,Case
3,Eileen,Dover
|
document.write() and
document.include().
<%
var files = [ "file1.txt", "file2.txt", "file3.js"];
for (var i = 0; i < 3; i++) {
document.write ("Content of file " + i + " [" + files[i] + "]\n");
document.include (files[i]);
}
%>
| Java code | Template code |
|---|---|
// Create a template instance from myFile.html
Template t = new Template ("myFile.html");
Writer writer = new OutputStreamWriter (System.out);
// Create a templateContext
Map aMap = new HashMap();
// Fill it with some simple objects
aMap.put ("number", new Integer (433));
aMap.put ("aString", "This is a string.");
// Add some structured objects
List aList = new ArrayList();
aList.add ("Foo");
aList.add (937);
aMap.put ("aList", aList);
Map anotherMap = new HashMap();
aMap.put ("subMap", anotherMap);
anotherMap.put ("date", new Date());
aMap.put ("anArray", new Object[] {5, 13, new Date(), 11});
// Expand the template, with aMap as templateContext
t.expand (aMap, writer);
|
<%
// Extract a Map value as a Javascript property
document.write (templateContext.aString + "\n");
// Invoke the java Date.getMonth method on a nested
// object property. Notice the convenient way of accessing
// key values in nested maps.
document.write ("Month: " +
templateContext.subMap.date.getMonth() + "\n");
// Iterate over a list
var n = templateContext.aList.length;
for (var i = 0; i < n; i++) {
document.write (templateContext.aList[i] + "\n");
}
// Iterate over an array
n = templateContext.anArray.length;
for (var i = 0; i < n; i++) {
document.write (templateContext.anArray[i] + "\n");
}
%>
|