0

I have the following Controller Action:

def doSomething() {
  [data: data as JSON]
}

On my GSP I can output the data params with:

${data}

Since data represents valid JSON I want to use it inside a JavaScript block on my GSP.

<script type="text/javascript">
var data = [
            { Date: "2015-09-14", DayOfMonth: 14, Type: "Views", Amount: 0, y1: 10, }
           ];
</script>

To replace a hard coded JSON variable. I know I can do the replacement with Strings like this:

<script type="text/javascript">
var data = "${data}";
</script>

or

<script type="text/javascript">
var data = "${raw(data)}";
</script>

The former works fine work primitive types like Strings but if I pass the JSON Array to the JavaScript variable it fails. When I print the content of the JavaScript data variable in the console I get:

[{&quot;Date&quot;:&quot;2015-09-13T22:00:00Z&quot;,&quot;DayOfMonth&quot;:14,&quot;Type&quot;:&quot;Views&quot;,&quot;Amount&quot;:1}]

How do I pass a JSON array to a JavaScript variable on my GSP page?

1 Answer 1

2

It appears to be an encoding problem that has yet to be resolved.

Solution 1 - disable encoder locally

<g:applyCodec encodeAs="none">
    var data = ${data};
</g:applyCodec>

Solution 2 - Affects the whole page

<%@page defaultCodec="none" %>

Solution 3 - Use a custom tag

class MyTagLib {
    static defaultEncodeAs = [taglib:'none']

    def writeWithoutEncoding = {attrs ->
        out << attrs.input
    }
}

and in the GSP page:

var data = <g:writeWithoutEncoding input="${data}"/>;

References: https://jira.grails.org/browse/GRAILS-11829 and http://aruizca.com/how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag/

Sign up to request clarification or add additional context in comments.

2 Comments

You could add the solution of creating a taglib too.
Thanks, after your suggestion I added a third way that uses a custom tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.