7

I want to pass data from controller to javascript by embedded data directly in view. (So there won't be additional requests.)

My first solution is to use as JSON in GSP like this:

<script>
  var data = ${invoice as JSON};
</script>

I don't think it's good idea since I have to use (Grails 2.2)

grails.views.default.codec = "none"

or (Grails 2.3)

grails {
  views {
    gsp {
      codecs {
        expression = 'none'
      }
    }
  }
}

Now, I found that I can create little taglib like this:

def json = { attrs, body ->
  out << (attrs.model as JSON)
}

And I can use following code in GSP:

<script>
  var data = <g:json model="${invoice}" />;
</script>

Now, the question. Is using taglib is best practice? If not, please give me the best solution.

4
  • How about sending the json String from the controller to the view, and using ${json.encodeAsJavaScript()}? Commented Jan 30, 2014 at 10:13
  • encodeAsJavaScript() gives me: var data = \u007b\u0022key1\u0022:\u0022val1\u0022\u002c\u0022key2\u0022:3.14\u007d Commented Jan 30, 2014 at 11:05
  • 2
    Oh right, in this case you need the raw data. ${raw(json)} Commented Jan 30, 2014 at 11:08
  • 2
    ${raw(json)} works! However json have to be String, not JSON object. Thanks. Commented Jan 30, 2014 at 12:06

3 Answers 3

3

Transforming the comment in answer. You can create your JSON String in the controller and pass it to the view. Grails 2.3.x have the raw codec that don't encode your content. More info about this codec here.

Example:

class MyController {
  def index() {
    String invoiceString = invoice as JSON
    [json: invoiceString]
  }
}

index.gsp

<script>
  var data = ${raw(json)};
</script>
Sign up to request clarification or add additional context in comments.

Comments

3

using grails 2.4.4.

Above answer did not worked for me.

so adding what worked for me.

Source: http://aruizca.com/how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag/

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

1 Comment

This is the only solution that worked for me on Grails 3.1.4
2

Now, I'm upgrading to Grails 3.2.4. I found that Sérgio Michels' method is still work. Just make sure jsonString is a String object.

<script>
  var data = ${raw(jsonString)};
</script>

If it is not a String object, you can use something like following code.

<script>
  var data = ${raw(mapInstance.encodeAsJSON().toString)};
</script>

1 Comment

This was why mine wasn't working! My method declared that I was returning a def object. Thank you!

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.