views:

56

answers:

1

Hi,

If a have a Java object (lets say a User object), and I use velocity to template the page so I can access a field in the user object like ${user.id}, is there an easy way to convert this into a javascript object (so I can access the fields of the User object)?

I can assign a value to javascript variable like

var id = "${user.id}";

but if i do

var user = "${user}";

this isn't true:

 id == user.id;

And I would rather not have to do

  var user = { id: "${user.id}" ...}
+2  A: 

Maybe you should transform your user object to a JSON.

You can create a utility method that uses reflection and gets each attribute from an object and put in a String. Maybe you can create an annotation to mark which attributes should be included in the JSON.

This way you send to your template something like this

"{id: '1', name:'stevebot'}"

And in you velocity file

var user = ${user};
Daniel Moura
Yeah, I think that might be the best idea. Ty for the suggestion.
stevebot