在 grails 服务中使用 g.render [英] Using g.render in a grails service
问题描述
我正在尝试在 grails 服务中使用 g.render,但似乎默认情况下没有向服务提供 g.有没有办法让模板引擎在服务中呈现视图?我可能会以错误的方式解决这个问题.我希望将视图从部分模板呈现为字符串,并将结果字符串作为 JSON 响应的一部分发回,以便与 AJAX 更新一起使用.
I'm trying to use g.render in a grails service, but it appears that g is not provided to services by default. Is there a way to get the templating engine to render a view in the service? I may be going about this the wrong way. What I'm looking to to is render the view from a partial template to a string, and send the resulting string back as part of a JSON response to be used with AJAX updates.
有什么想法吗?
推荐答案
我完全同意 John 的论点 - 在服务中使用 GSP 通常是一个糟糕的设计决策.但没有规则无一例外!如果您仍然想这样做,请尝试以下方法:
I totally agree with John's argumentation - doing GSP in services is generally a bad design decision. But no rules without exceptions! If you still want to do this, try the following approach:
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.
Using the gspTagLibraryLookup bean you can of course access every other desired taglib in a service.
这篇关于在 grails 服务中使用 g.render的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!