-
Notifications
You must be signed in to change notification settings - Fork 18
Invoking templates in controllers
There are two ways one can designate a template to render in controller actions.
The controller must be a sub-class of JapidController in the Japid module to use this method.
The JapidController provides a method called renderJapid(Object… args) which is very similar to the render() method provided by the original Play’s Controller super class. The renderJapid method looks for a template named after the current controller and action to render the data.
For example, if the current controller class is controllers.japid.SampleController and the action (method) name is renderByPosition(), then the default rendering template is ${App root}/app/japidviews/japid/SampleController/renderByPosition.html
The parameter binding is by the convention of Java method invocation, in contrast to the way the default Play controllers binding to the Groovy based templates, where bindings are by variable names.
Sample:
controller:
public static void renderByPosition() { String s = "hello,renderByPosition!"; int i = 100; Author a = new Author(); a.name = "author1"; Author2 a2 = new Author2(); a2.name = "author2"; renderJapid(s, i, a, a2, a2); }
Template: renderByPosition.html
` import models.japidsample.Author ` import models.japidsample.Author2 ` args String ss, int ii, Author au1, Author au2, Author2 au22 got: $ss got: $ii got: $au1.name, $au2.name, $au22.who
Pros: The controllers don’t have compile-time dependence on the Java code derived from the Japid template html files, which means there is no extra steps in developing Japid and Japid can be considered as a “drop-in” replacement of the Play’s template engine – almost.
Cons: It’s slightly slower than explicit template binding as explained below. No compile-time error checking. No cache control possible in action method.
In explicit mode, developers use “play japid:gen” to transform html templates to intermediate Java classes and invoke the Java object directly in the action method.
For example, a template file named composite.html is transformed to Java class named composite.java (Note the file name cases) and the controller code simply invoke the render method on the template Java code:
RenderResult render = new composite().render(post); throw new JapidResult(render);
Note: the RenderResult object is wrapped in a JapidResult that is thrown out to the Play’s low level code.
The render method’s signature matches those specified in the html template’s args line.
Pros: fast with compile-time error checking. More advanced cache controls requires use of this mode, since RenderResult can be cached. The controller does not need to inherit from the JapidController.
Cons: manual transformation is required in “cold dev” mode. More tedious than the implicit mode. The action code looks messier.