我正在尝试在 grails 服务中使用 g.render,但似乎 g 默认情况下不提供给服务。有没有办法让模板引擎在服务中呈现视图?我可能会以错误的方式解决这个问题。我希望将视图从部分模板呈现为字符串,然后将生成的字符串作为 JSON 响应的一部分发回以用于 AJAX 更新。
有什么想法吗?
我完全同意 John 的论点——在服务中进行 GSP 通常是一个糟糕的设计决策。但没有规则没有例外!如果您仍想这样做,请尝试以下方法:
class MyService implements InitializingBean {
boolean transactional = false
def gspTagLibraryLookup // being automatically injected by spring
def g
public void afterPropertiesSet() {
g = gspTagLibraryLookup.lookupNamespaceDispatcher("g")
assert g
}
def serviceMethod() {
// do anything with e.g. g.render
}
}
使用 gspTagLibraryLookup bean,您当然可以访问服务中所有其他所需的 taglib。
现在使用 PageRenderer 在 Grails 2 中变得更加简单。例如:
class SomeService {
def groovyPageRenderer
void someMethod() {
String html = groovyPageRenderer.render(view: '/email/someTemplateName')
}
}
API - http://grails.org/doc/latest/api/grails/gsp/PageRenderer.html
更完整的例子 - http://mrhaki.blogspot.com/2012/03/grails-goodness-render-gsp-views-and.html
我的建议是在控制器中执行此操作。服务应该具有可重用的逻辑并且不依赖于视图模板,将这项工作留给控制器。使用该服务获取您需要传递给模板的数据,但将与模板交互的工作留给控制器。
这是一个类似于Stefan 的解决方案,但更简单一些
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
class MyService implements ApplicationContextAware {
private ApplicationTagLib g
void setApplicationContext(ApplicationContext applicationContext) {
g = applicationContext.getBean(ApplicationTagLib)
// now you have a reference to g that you can call render() on
}
}