Javascript – How I access a variable from JavaScript and Grails

grailsgspjavascript

I have a Grails variable which is of type JASONList that is rendered in a template.

Is there a way to access this list from inside a JavaScript function?

Let's say I want onresize to fit all the objects on the screen. Without making a database call and refetching the entire list from Ajax…

Let's say the template does something like this:

<g:each var="report" in="${reportList?.myArrayList}">
  <li style="display:inline; list-style:none;">
    <img src="  ${report?.img}">
  </li>
</g:each>
<script type="text/javascript">
    function resize(list) {
        if (list.size <givenSize) // Pseudocode
            list.subList() // Pseudocode
    }
    window.onresize = resize("${reportList}")
</script>

The problem with this is that for some reason Grails gsp does not render "${reportList}" as a list. Instead it renders it as the string "${reportList}".

I am probably thinking of this problem completely wrong, but is there a way to resize these objects or get them through document.getElementById or something of that nature?

The $reportList is populated by POJO as JSON conversion…

Best Answer

Grails variables only exist on the server side. JavaScript runs in the browser (client side). Everything that's sent to the browser is a string, so while you can use Grails to generate a piece of JavaScript like window.onresize = resize("${reportList}"), the browser will only see the string that ${reportList} evaluates to.

That means that, if you use Grails to pass a variable to the resize() JavaScript function, the parameter (list) will only ever be a string - you won't be able to access server-side list methods like list.size or list.subList(), because the list variable is no longer a list; it's just a string.