Hello XML World - Same thing as
the simple grocery list, but in XML. Directives are either embedded in the markup (as tdir
attributes) or in a separate properties file (where directives are referenced by the id
attributes).
Looking at the Templates
The primary purpose of this example is to show how we can also use the BTemplate on XML
just as easily as with HTML. So what are the key points?
First of all, let's take a look at the templates. Depending on a page property in the
HTTP Request, we load one of two templates. Template 1 contains directives embedded in the
markup. Instead of using the class attribute, we embed them in a tdir
attribute.
...
<title tdir="Dir::Get_Data.HelloWorld.Title">[Title]</title>
<descr tdir="Dir::Get_Data.HelloWorld.Descr">[Descr]</descr>
...
In order to make this work, our DTD must
specifically allow for this. We do this by specifying that all elements may contain a tdir
attribute.
Now in some cases, it may not be possible to modify the DTD (ie. if the DTD is a
standard, or defined by some 3rd party). In cases like this we can use the id
attribute (or whatever attribute the DTD defines as being of type ID).
...
<title id="Title">[Title]</title>
<descr id="Descr">[Descr]</descr>
...
In this latter approach, the ids act as keys to the actual directives which are stored
in a separate properties file, like this:
Title = Dir::Get_Data.HelloWorld.Title
Descr = Dir::Get_Data.HelloWorld.Descr
...
In both of these cases, the template component locates the directives and processes
them in much the same way as with the HTML templates. Directives are matched with a node
and processed accordingly.
Custom Attribute Names
The one other thing worth noting here is that our template does not have to use the
"id" or "class" attributes to reference directives. While these are
the default, when we create a DefaultTemplateView, we can pass in the attribute names that
should be considered instead. In this case, we specified that while the ID attribute was
still "id", the directives attribute (of type CDATA) was in this case called
"tdir".
Here's how we create the template views, both when the directives are embedded in the
template, and when they are stored in a separate properties file:
TemplateView tv = null;
if (useIDTemplate) {
String propFileName = "HelloWorld3a.properties";
Properties props = new Properties();
try {
props.load(this.getClass().getResourceAsStream(propFileName));
tv = new DefaultTemplateView(node,
"id", new MapStateMap(props));
} catch (IOException e) {
System.out.println ("Fatal err loading
properties file:"+e);
}
} else {
tv = new DefaultTemplateView(node, "tid", "tdir");
}
As you can see that's really all there is too it. The view and the component are smart
enough to take care of the rest. |