如何在视图中调用 Grails 服务?
简单的问题: 我有一个服务类(比如说 helpersService
)和一个方法 def ConstructionURI(params)
。 如何从模板视图调用此方法。
我尝试了以下代码但没有成功
<% def helpersService = new HelpersService() // or def helpersService
%>
<img src="${helpersService. constructURI(params)}"/>
但我得到以下结果:
No signature of method: com.HelpersService. constructURI() is applicable for argument types...
或者(如果我使用 def helpersService
)
Cannot invoke method constructURI() on null object
有什么想法吗?
Simple question :
I have a service class (let's say helpersService
) and a method def constructURI(params)
.
How can I call this method from a template view.
I have tried the following code without success
<% def helpersService = new HelpersService() // or def helpersService
%>
<img src="${helpersService. constructURI(params)}"/>
But I get the following result:
No signature of method: com.HelpersService. constructURI() is applicable for argument types...
or (in case I use def helpersService
)
Cannot invoke method constructURI() on null object
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
服务不适合在视图内部使用。您可以创建一个 TagLib,在其中可以通过依赖项注入获取对服务的引用。
Services are not intended to be used inside views. You could create a TagLib where you can get a reference to the service via dependency injection.
假设您的视图由控制器呈现,一种更简单的方法是将服务的引用从操作传递到模型中的视图,即:
然后可以按照您在视图中期望的方式使用它。对于由视图呈现的模板,显然您还需要传递对模板的引用。不过需要澄清的是,S. Puchbauer 是对的。服务实际上并不应该在视图中使用,并且您可能会遇到难以诊断的问题,尤其是与事务和 Hibernate 会话相关的问题。
An easier method, assuming your view is being rendered by a Controller, is to just pass a reference to the service from the action to the view within the model, i.e.:
It can then be used as you would expect within the view. For a template rendered by a view, obviously you need to pass the reference to the template as well. Just to be clear though, S. Puchbauer is right; services are not really supposed to be used within Views, and you may experience difficult to diagnose problems, especially related to transactions and the Hibernate session.
我发现这个常规内联代码可以工作:
您可以像这样调用服务的函数:
I found out, that this groovy inline code works:
You can call functions of the service just like this:
好吧,我找到了使用以下代码的解决方法:
但是,最好通过依赖注入使用服务,所以我将尝试 Siegfried 建议。
Well I have found a workaround with the following code :
However it is better to use Service via dependency injection, so I will try out Siegfried advice.
您可以轻松地做到这一点,而无需使用 set 标签创建标签库:
我在这里找到了这个解决方案: http://mrhaki.blogspot.com/2013/08/grails-goodness-use-services-in-gsp.html
You can do this easily without creating a tag lib by using the set tag:
I found this solution here: http://mrhaki.blogspot.com/2013/08/grails-goodness-use-services-in-gsp.html