Wednesday, April 11, 2012

gwt-hogan: Hogan templating goodness for GWT

GWT is kind of created from the perspective of a desktop developer. But what if you need to work with a designer who knows how to work with html and that's it? Most web developers use some sort of templating system, but GWT doesn't have anything like this. I've came up with a proof of concept for a project that I was going to do in GWT to allow the graphic designer to work using the Twitter's Hogan templating engine.

Usage is pretty easy:

You create a templated widget object in Java (GWT). Parameter must use Google's GWT JSON API.
public class MyTemplate extends HoganWidget {
  public Test(){
    addParameter("planet", new JSONString("world"));

and a template file in the same package:
Hello <span id="planet"></span> {{planet}}

You can then use the template like this. The {{planet}} will be replaced with the parameter which you passed.
MyTemplate myTemplate = GWT.create(MyTemplate.class);


Using GQuery is also possible. This allows for dynamically changing the content of the template after the template has been set up.
public class MyTemplate extends HoganWidget {
  public void onLoad(){
And your template would look something like this:

Hello <span id="planet"></span>

Data Binding

I also played around with binding data. There's various ways of doing this, but I used the Gwt AutoBeans framework. See for more details.

So you have a Data Object interface

public interface TestData {
    public String getField1();
    public void setField1(String v);

With a factory:

public interface TestDataFactory extends AutoBeanFactory {
    AutoBean<TestData> data();

And in your widget you bind the generated object to the hogan template:

public class MyTemplate extends HoganWidget {
  public Test(){
    TestDataFactory beanFactory = GWT.create(TestDataFactory.class);
    TestData test1 =; //get a managed TestData object

    addParameter("data", test1);

And then in your template, you can use that object:

Field1: {{data.field1}}

Check it out, and feel free to drop some comments or fork it and improve it:

1 comment:

  1. Jayme Silvestri
    I have been reading out many of your stories and i can state clever stuff. I will definitely bookmark your site.