Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Java object into closure template?

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?

like image 487
huy Avatar asked Jan 29 '12 02:01

huy


1 Answers

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.

like image 157
bolinfest Avatar answered Oct 11 '22 19:10

bolinfest