Create a data-model

In simple cases you can build data-models using java.lang and java.util classes and custom Java Beans:

  • Use java.lang.String for strings.

  • Use java.lang.Number descents for numbers.

  • Use java.lang.Boolean for boolean values.

  • Use java.util.List or Java arrays for sequences.

  • Use java.util.Map for hashes.

  • Use your custom bean class for hashes where the items correspond to the bean properties. For example the price property of product can be get as product.price. (The actions of the beans can be exposed as well; see much later here)

For example, let's build the data-model of the first example of the Template Author's Guide. For convenience, here it is again:

(root)
  |
  +- user = "Big Joe"
  |
  +- latestProduct
      |
      +- url = "products/greenmouse.html"
      |
      +- name = "green mouse"  

This is the Java code fragment that builds this data-model:

// Create the root hash
Map root = new HashMap();
// Put string ``user'' into the root
root.put("user", "Big Joe");
// Create the hash for ``latestProduct''
Map latest = new HashMap();
// and put it into the root
root.put("latestProduct", latest);
// put ``url'' and ``name'' into latest
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");  

For the latestProduct you migh as well use a Java Bean that has url and name properties (that is, an object that has public String getURL() and String getName() methods); it's the same from viewpoint of the template.


Page generated: 2007-12-05 00:36:54 GMT FreeMarker Manual -- For FreeMarker 2.3.11