Reputation: 3396
In a play framework 1.2.4 Controller, is it possible to get the contents of a template or tag as a String before output to the browser?
I want to be able to do this:
String json = renderAsString("/path/to/template.json", var1, var2);
//then use json as the body of a Play.WS request body.
Upvotes: 4
Views: 2344
Reputation: 5288
In addition to green answer.
If creating a json is what you want you would better use gson rather than building your own string with groovy templates. Gson is included in Play Framework 1.2.X.
You can find more information here. Example from Gson doc:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
//json is {"value1":1,"value2":"abc"}
You can also use Flexjson instead of gson.
Upvotes: 0
Reputation: 14373
The solution is based on the assumption that you are talking about PlayFramework 1.x
If you are using Groovy template engine:
Map<String, Object> args = ...
Template template = TemplateLoader.load("path/to/template.suffix");
String s = template.render(args);
And you have a shortcut way if you are using Rythm template engine:
String s = Rythm.render("path/to/template.suffix", param1, param3...);
Or you can also use named arguments:
Map<String, Object> args = ...
String s = Rythm.render("path/to/template.suffix", args);
Note the Groovy way also works for Rythm if your template file is put under app/rythm
folder.
Upvotes: 3