fab*_*474 6 service grails view gsp
简单的问题:我有一个服务类(比方说helpersService)和一个方法def constructURI(params).如何从模板视图中调用此方法.
我尝试了以下代码但没有成功
<% def helpersService = new HelpersService() // or def helpersService
%>
<img src="${helpersService. constructURI(params)}"/>
Run Code Online (Sandbox Code Playgroud)
但我得到以下结果:
No signature of method: com.HelpersService. constructURI() is applicable for argument types...
Run Code Online (Sandbox Code Playgroud)
或(如果我使用def helpersService)
Cannot invoke method constructURI() on null object
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
假设您的视图由Controller呈现,更简单的方法是将操作的引用从操作传递到模型中的视图,即:
class someController {
def someService
def someAction = {
render(view: 'someView', model: ['someService': someService])
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以在视图中使用它.对于由视图呈现的模板,显然您还需要将引用传递给模板.但是要清楚,S.Puchbauer是对的; 实际上不应该在Views中使用服务,并且您可能会遇到难以诊断的问题,尤其是与事务和Hibernate会话相关的问题.