1
votes

This seems like it should be simple to me but I'm struggling! I'm working on my second grails app, the first used angular.js but I can't this time around due to legacy browser requirements. I have built some of my page templates using the .gsp template hooks (g:each, g:if etc) and some JQuery to do some basic presentational stuff. The problem now is that I need to use the data that the .gsp is accessing (basic http get request along with the page load) within my JavaScript.

I could just make the controller render the data as JSON but then the grails template hooks would stop working.

I could fetch all the values from the DOM and build a local model in JS OR I could do some horrible mix-up of outputting data using .gsp g:each and then saving each one to JS inline but both processes seem ridiculous.

I could get the controller to respond with data for the .gsp AND render as JSON separately for the JS but this just seems wrong!

I'm at a loss as to how to do this, please offer any suggestions!

1
can't you use data- attributes? - charlietfl
that's what I'm now doing after seeing Donal's reply below. It seems like going the long way round though as I'm dealing with big tables of data, so I have to be really careful with my naming. What I was hoping for was an EASY way to access the full model including all it's properties in one go, rather than having to rebuild it all from it's component parts. - bitfidget

1 Answers

0
votes

Using the simple example of an action that returns this model

def myAction() {
  [name: 'bob']
}

You basically have two choices

1. Store the data in JavaScript variables

<script type="text/javascript">
  var name = '${name}';
  // now do something with the name
</script>

2. Store the data in data- attributes

<div id="name" data-name="${name}"></div>

You can then read the name using JavaScript/jQuery

var name = $('#name').data('name');