Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails controller variables not visible in the views

I am quite new to grails. I just noticed that variables in the controller are not visible in the view. I only can get the variable values when I assign it to a scope. Is this the standard Grails way or am I doing this wrong. Also, is the params scope the correct one to use or should I use sessions, servletContext?

In the Controller

String uploadLocation = grailsApplication.config.uploads.location.toString()
params.put "upLoc", uploadLocation

In the View

<td> <input type="text" value="${params.get('uploc')}/${fileResourceInstance.decodeURL()}"></input></td>

I'm very familiar with Ruby on Rails and this is handled very differently in RoR. Thanks.

like image 205
ibaralf Avatar asked Apr 08 '11 22:04

ibaralf


2 Answers

You can do it like Maricel say, but there's another way (I think it's a default way to do): return the values you want to pass to the view in action function. For example

def test = "abc"
def num = 3

return [testInView: test, numInView: num]

Then in view you can access ${testInView}, ${numInView}

Another slightly different way: you can neglect the "return" keyword, it's "groovy way" to return the last value of the function.

like image 149
Hoàng Long Avatar answered Nov 13 '22 23:11

Hoàng Long


You need to pass your variable as part of the model through the render method in your controller action, like this:

String uploadLocation = grailsApplication.config.uploads.location    
render(model: [uploadLocation: uploadLocation])

Then in the view you can just do:

<td> 
   <input type="text" value="${uploadLocation}/${fileResourceInstance.decodeURL()}"/>
</td>

On the other hand, if this is a value that is defined in the Config.groovy, you can do this as well in your gsp:

<%@ page import="org.codehaus.groovy.grails.commons.ConfigurationHolder as CH" %>

<td> 
   <input type="text" value="${CH.config.uploads.location}/${fileResourceInstance.decodeURL()}"/>
</td>

For more info check the Grails docs.

like image 22
Maricel Avatar answered Nov 14 '22 00:11

Maricel