Search code examples
google-app-enginegroovygaelyk

Gaelyk - How Can I pass model objects between Controller and View


I am just starting to use Gaelyk.

I was expecting it to behave like Spring MVC; I create my model object in the controller.groovy, and the format the model object in the .gtpl.

In the controller I do this

def model = new MyModel()
model.setMyId(2)

and in the .gtpl I do this

<h1>Test ${model.myId}</h1>
<p>
    Model object is ${model}
</p>

However when I run this I get a MissingPropertyException

groovy.lang.MissingPropertyException: No such property: model for class: SimpleTemplateScript1

In the tutorial examples the model object is shoehorned into an Attribute of javax.servlet.http.HttpServletRequest which IS accessible to the .gtpl.

Is this really the only way pass data between the controller and the template ? I would feel cleaner if I could avoid polluting the Request (or Response) objects.


Solution

  • I think your only option is the request object (as you say). You set the variables into the request object like:

    def model = new MyModel()
    model.setMyId(2)
    request.model = model
    
    forward 'view.gtpl'
    

    Then, in view.gtpl you do:

    <h1>Test ${request.model.myId}</h1>
    <p>
        Model object is ${request.model}
    </p>
    

    As request is short-lived, I wouldn't say it's polluting the Request object, more utilising it ;-)

    And it's miles better than using (for example) the session object

    PS: I realise you probably already know how all this works, as you state that the docs say to use the request object :-/