Gaelyk - 如何在控制器和视图之间传递模型对象

发布于 2024-11-11 08:03:05 字数 675 浏览 4 评论 0原文

我刚刚开始使用 Gaelyk。

我期望它表现得像 Spring MVC;我在controller.groovy 中创建模型对象,并在.gtpl 中设置模型对象的格式。

在控制器中我执行此操作

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

,在 .gtpl 中我执行此操作

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

但是,当我运行此命令时,我收到 MissingPropertyException

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

在教程示例中,模型对象被硬塞到 javax.servlet 的属性中。 http.HttpServletRequest 可以通过 .gtpl 访问。

这真的是控制器和模板之间传递数据的唯一方法吗? 如果我可以避免污染请求(或响应)对象,我会感觉更干净。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别低头,皇冠会掉 2024-11-18 08:03:05

我认为你唯一的选择是请求对象(正如你所说)。您将变量设置到请求对象中,如下所示:

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

forward 'view.gtpl'

然后,在 view.gtpl 中,您执行以下操作:

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

由于 request 是短暂的,我不会说它污染了 Request 对象,更多地利用它;-)

而且它比使用(例如)会话对象要好得多

PS:我意识到你可能已经知道这一切是如何工作的,正如你所说的文档所说的使用请求对象:-/

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

深海不蓝 2024-11-18 08:03:05

添加到 tim_yates 响应中,您可以使用以下内容包装整个 gtpl:

controller:

request.model = [myId:123]

view:

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

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>
...
<% } %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文