Velocity, stringify JSON object in template

5.3k views Asked by At

I have this in my velocity templates:

<div>$config.get("locale")</div>

I want to have the whole $config object as stringified JSON in a data attribute of a html element so I can access/parse it in my client-side javascript. I thought of something like this:

<div data-config="$config.stringify()">...</div>

Doesn't seem to work that way - so how can I do that? Is there something like JSON.stringify in Velocity?

thx

1

There are 1 answers

0
Jason Sperske On

I'm not aware of a helper function like stringify() as part of Velocity, but you can implement one yourself rather easily with something like Gson like this:

public String stringify() {
  return (new Gson()).toJson(this);
}

Then change your Velocity to look like this:

<div data-config="$config.stringify">...</div>