Playing with Wicket’s templates
Wicket comes with some templating facilities. They’re often handy, especially when integrating JavaScript components.
Yet, for some reasons I don’t get, these functionalities aren’t much advertised. Anyway, let’s dig in !
Basically, this templating is about some text containing variables, for example ${variable}, whose values are provided through Java code.
Let’s take a simple example, a template file named javascript.tpl containing :
alert('${variable}');
Wicket is nice enough to provide an easy to access the templates as package resources, through the PackagedTextTemplate class :
| Java | | copy | | ? |
public PackagedTextTemplate(final Class< ? > clazz, final String fileName) |
For example :
| Java | | copy | | ? |
PackagedTextTemplate jsTemplate = new PackagedTextTemplate(this.getClass(), "javascript.tpl"); |
Thus the template can be next to the .html page and the Java class using it, making the whole quite cohesive.
Providing the variables is done through a simple Map :
| Java | | copy | | ? |
Map< String , Object > parameters = new HashMap< String , Object >(); |
parameters.put("variable","test working"); |
And then, you most probably want to include this template in some html. Wicket provides you different options :
- as an header contribution :
Java | copy | ? add(TextTemplateHeaderContributor.forJavaScript(jsTemplate, new Model((Serializable) parameters)));
- directly next to some element in the html file:
Java side :
Java | copy | ? Label myScript = new Label("myScript", new JavaScriptTemplate(jsTemplate).asString(parameters));
myScript.setEscapeModelStrings(false);
add(myScript);
Html side :
<wicket:container wicket:id="myScript"></wicket:container>
You may have noticed that, in both cases, I didn’t provided the surrounding script tag (and the appropriate inner wrapping). Fear not, Wicket does it for you !
Indeed, the rendered html is :
<script type="text/javascript"><!--/*--><![CDATA[/*><!--*/
alert('test working');
/*-->]]>*/</script>
If the template was about some CSS stuff, one would just need to warp it using a CssTemplate instead of the JavaScriptTemplate.
A bit more info are available there Including CSS resources.
++
joseph

