Smart Tech for a better Web
First I created an action:
This will call JSTemplateService when I request for localhost/templates.action (ending of this “file” is to be configured in your struts application). It uses then a JSP file on success to render the output.
Let’s look at the JSTemplateService.java file. I leave out all setters/getters and class definition stuff. Basically this is my execute() method, which is called once the request arrives.
Then I open streams to hogan.js and templates.js. The second file does is the place where my templates reside. We will look at it later.
Make sure Hogan.js is available for Struts, which is is usually in /src/main/resources/packagename.
Another note, please take care not do decorate your request with for example Sitemesh. If you use sitemesh open decorators.xml and exclude templates.action from the decorations:
(this is for Sitemesh 2)
I have used the compilation as a Struts 2-Action which means, you always compile the templates this action is called. The file can be stored in the Browser cache, which will reduce compilations. If you want to do compilation one time only, then you probably should create a Spring bean in singleton scope or have a similar mechanism.
Lets finally look at our templates.js file.
First line is my mustache syntax. I put this into the Hogan.compile method and the asString parameter to it. Hogan.compile will then return the render function as a String. This is then put into the already mentioned Java Collection namely “compiled” under the name “hello”.
First, you need to include hogan.js and then our templates. Once done, you can create a HoganTemplate object, which I store in the template variable. Here you need to put your rendered function into the templates.r property. This is the property into which Hogan.compile would put it for you too, if using it at browser side. Finally you can render your template with calling it with the params to your likings. In my case “Hello Christian” will be shown.