Passing Java object to closure pattern?

As far as I know, the Google Closure Template does not allow you to pass a Java object into a template (compared to FreeMarker ). Therefore, I can not 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 think that if I want to do this, I probably have to write a custom function that uses Reflection to turn the course object into a map? I do not experience Java Reflection. Is this feature available?

+6
source share
1 answer

In plovr, I created the utility SoyDataUtil.java , which takes JsonElement and converts it to SoyData . Admittedly, you can only find this if you are already using Gson , but the nice thing about this approach is that Gson will most likely take care to setter reflection for you. For example, I believe that you should do this:

 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 to use Gson for reflection in order to turn courses into JsonElement . Not sure if you want to add these dependencies (although the code from plovr is pretty small - you can just copy it directly), but this may be the most appropriate solution.

+7
source

Source: https://habr.com/ru/post/907134/


All Articles