Search code examples
javascriptgrailsgroovy

How to pass a javascript variable into a groovy block


I need to manage a groovy list object in my javascript function. I have a groovy block into a javascript function. I tried with this:

var obj = ${mediaObjectInstanceList as grails.converters.JSON}[index];

and this:

var obj = ${mediaObjectInstanceList.get(index)};

but both are wrong. In the second I would specify the "index" int javascript variable out of the groovy block.


Solution

  • As answered by injecteer, you can't do that. Mostly because :

    • groovy blocks are executed server side : they can't be aware of variables in javascript only know by the browsers.
    • javascript is executed client side, ie. browsers don't know the variable mediaObjectInstanceList (only known by your grails application).

    Two (main) solutions :

    • you don't know your index when the page is generated (no params in your request) => You have to generate the whole array server side (groovy) to be available at client side (javascript).

      var mediaObjectInstanceListInJS = new Array( ${mediaObjectInstanceList.collect { it as JSON}.join(',')} ); var someVal = mediaObjectInstanceListInJS[index];

    • you already have the index server side (with params in your request) => you can get in groovy block only your selected object :

      var someVal = ${mediaObjectInstanceListInJS[params.index] as JSON} ;