jeudi 3 novembre 2011

Use Sitebricks with Freemarker

Few months ago, I've started to use Guice and Sitebricks for my web applications instead of the Spring MVC architecture I was working with for years. And I have to say I'm now a Guice addict. Sitebricks is a really great framework but there is one thing I don't get use to it : the default MVEL based templating engine. I've switch to Freemarker and here is how I did it.

If you want to switch to Sitebricks, you should also know that there is a lack of documentation but the user group is really active.

Here is  the Renderable interface I've designed :

public interface Renderable {

 public Map<String, Object> getModel();
 public String getTemplate();
 
}

Each Renderable object can be process by the TemplateEngine :

public class TemplateEngine {

 private Configuration configuration;
 
 public TemplateEngine() {
  this.configuration = new Configuration();
  this.configuration.setClassForTemplateLoading(this.getClass(), "/");
  this.configuration.setObjectWrapper(new DefaultObjectWrapper()); 
 }
 
 public String render(Renderable renderable) {
  try {
   Template template = configuration.getTemplate(renderable.getTemplate());
   Writer out = new StringWriter();
   template.setEncoding("UTF-8");
   template.process(renderable.getModel(), out);
         out.flush();
         return out.toString();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
  catch (TemplateException e) {
   e.printStackTrace();
  }
  return "Templating Error";
 }
 
}

The trick is to transform all your Sitebricks pages annotated with @Show into a service annotated with @Service. Each service will implement the Renderable interface and the method getTemplate() should return the value previously given as parameter to @Show.
Then use the Reply API to send your template back to the browser.

Reply.with(templateEngine.render(this)).type("text/html; charset=utf-8");

For example :

@Service
public class TestService implements Renderable {

 @Get
 public Reply<String> get() {
  // do something
  return Reply.with(templateEngine.render(this)).type("text/html; charset=utf-8");
 }

 @Override
 public Map<String, Object> getModel() {
  Map<String, Object> model = initModel();
  model.put("test", "test");
  return model;
 }

 @Override
 public String getTemplate() {
  return "test.ftl";
 }

}

And here you are. Freemarker is now your templating engine in Sitebricks.

0 commentaires:

Enregistrer un commentaire