Accueil > professional > Playing with Wicket’s templates

Playing with Wicket’s templates

[Ce billet est également disponible en français.]

Wicket comes with some templating facilities. Nothing fancy, but still they’re quite handy, especially when integrating JavaScript components.

These functionalities aren’t much advertised and I would say even quite unknown. So, 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 :


Wicket is nice enough to provide an easy to access the templates as package resources, through the PackagedTextTemplate class :

public PackagedTextTemplate(final Class clazz, final String fileName)

For example :

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 :

Map parameters = new HashMap();
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 :
    add(TextTemplateHeaderContributor.forJavaScript(jsTemplate, new  Model((Serializable) parameters)));
  • directly next to some element in the html file:
    Java side :

    Label myScript = new Label("myScript", new JavaScriptTemplate(jsTemplate).asString(parameters));

    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');

If the template was about some CSS stuff, one would just need to wrap it using a CssTemplate instead of the JavaScriptTemplate.

A bit more info are available there Including CSS resources.


Étiquettes : , , , ,
  1. can
    avril 8, 2011 à 6:37

    Thanks! Later I use antlr ) but I didn’t know nothing about templates in wicket.

  1. juin 19, 2010 à 2:01

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:


Vous commentez à l'aide de votre compte Déconnexion /  Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion /  Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion /  Changer )


Connexion à %s

%d blogueurs aiment cette page :