开发者

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.


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 :-/


adding to the tim_yates response you can wrap your entire gtpl with this:

controller:

request.model = [myId:123]

view:

<% request.model.with{ %>
...
<p> this is my id: ${myId} </p>
...
<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜