HTML.Template.java

How to use HTML.Template

Nested Loops

Very often, one needs to use nested loops in an application, for example, print a list of employees, along with all their projects. We need to loop through the employees, and for each employee, loop through his projects.

The java is similar to that for single loops. All you have to do, is make your inner loop a parameter in your outer loop. ie, your Hashtables in the outer loop would contain one element that is a Vector instead of a String.

The inner Vector is identical to any other loop Vector.

Example

Create a template called test-nest.tmpl:

<tmpl_loop employee_info>
<p>
Name: <tmpl_var name><br>
Job: <tmpl_var job><br>
Projects: <tmpl_unless projects>none<tmpl_else><br>
<ul><tmpl_loop projects>
<li><tmpl_var name></li></tmpl_loop>
</ul></tmpl_unless>
</p>
</tmpl_loop>

And the corresponding java code Test4.java:

import HTML.Template;
import java.util.*;

public class Test4 {
	public static void main(String [] args) {
	try {
		// Create the Template object
		Template t = new Template(args);

		// Set some parameters
		Vector v = new Vector();
		Hashtable h = new Hashtable();
		h.put("name", "Philip");
		h.put("job", "programmer");

		Vector v2 = new Vector();
		Hashtable h2 = new Hashtable();
		h2.put("name", "HTML.Template");
		v2.addElement(h2);

		h2 = new Hashtable();
		h2.put("name", "httptype");
		v2.addElement(h2);

		h.put("projects", v2);

		v.addElement(h);

		h = new Hashtable();
		h.put("name", "Bob");
		h.put("job", "Web designer");

		v2 = new Vector();
		h2 = new Hashtable();
		h2.put("name", "WD2");
		v2.addElement(h2);

		h2 = new Hashtable();
		h2.put("name", "btob");

		v2.addElement(h2);
		h.put("projects", v2);

		v.addElement(h);
		h = new Hashtable();
		h.put("name", "John");
		h.put("job", "Manager");

		v.addElement(h);

		t.setParam("employee_info", v);

		System.out.print(t.output());
	} catch(Exception e) {
		System.err.println(e);
	}
	}
}

Compile and run the code. This time, we use a different format to pass the template parameters to the constructor. We use the String array constructor, and template parameters are passed on teh command line. To run it, use this:
java Test4 filename test-nest.tmpl
If all goes well, you should see this:

<p>
Name: Philip<br>
Job: programmer<br>
Projects: <br>
<ul>
<li>HTML.Template</li>
<li>httptype</li>
</ul>
</p>

<p>
Name: Bob<br>
Job: Web designer<br>
Projects: <br>
<ul>
<li>WD2</li>
<li>btob</li>
</ul>
</p>

<p>
Name: John<br>
Job: Manager<br>
Projects: none
</p>