Passing data from controller to JavaScript in GSP
grails, javascript, json
Solution
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>
Problem
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.