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);
RootPanel.get().add(myTemplate);

GQuery

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(){
    super.onLoad();
    $("#planet").text("world");
  }
}
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 http://code.google.com/p/google-web-toolkit/wiki/AutoBean 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 = beanFactory.data().as(); //get a managed TestData object
    test1.setField1("foo");

    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:
https://github.com/ustramooner/gwt-hogan

CouchPotato NzbIndex.com Support

I have made a nzbindex.com plugin for CouchPotato. This allows you to do search and download nzbs automatically from nzbindex.com (which is my favourite nzb search engine).

Get it at https://github.com/ustramooner/CouchPotato