As far as I know, Google Closure Template doesn't allow passing Java object into the template (as compared to FreeMarker). So I can't really do something like:
// Java file
class Course {
...
public function getName() {
return name;
}
}
// Main function
public static void main(String args[]) {
// Get all courses
List<Course> courses = Courses.getAllCourses();
Map<String, Object> params = new HashMap<String, Object>();
params.put("courses", courses);
String out = tofu.newRenderer("template.listCourses").setData(params);
}
// Soy file
/**
* @param courses List of courses
*/
{template .listCourses}
Courses List! <br/>
{foreach $course in $courses}
New Course: {$course.name}
{/foreach}
{/template}
I'm thinking if I want to do this I probably have to write a custom function that uses Reflection to turn Course object into a Map? I'm not experienced with Java Reflection. Is there such a function available?
In plovr, I created a utility, SoyDataUtil.java, which takes a JsonElement and converts it into a SoyData. Admittedly, you may only find this useful if you are already using Gson, but the nice thing about this approach is that Gson is likely to take care of the getter/setter reflection for you. For example, I believe you should be able to do:
JsonElement json = (new Gson()).toJsonTree(courses);
SoyData soyData = SoyDataUtil.jsonToSoyData(json);
Map<String, Object> params = new HashMap<String, Object>();
params.put("courses", soyData);
The trick is leveraging Gson to do to the reflection to turn courses
into a JsonElement
. Not sure whether you're willing to add these dependencies (though the code from plovr is quite small -- you can just copy it directly), but this may be the most expedient solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With