Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using g.render in a grails service

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.

Any thoughts?

like image 511
aasukisuki Avatar asked Nov 22 '09 02:11

aasukisuki


2 Answers

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
    }
}

Using the gspTagLibraryLookup bean you can of course access every other desired taglib in a service.

like image 82
Stefan Armbruster Avatar answered Oct 03 '22 19:10

Stefan Armbruster


It's even simpler now in Grails 2 with the PageRenderer. e.g.:

class SomeService {
    def groovyPageRenderer

    void someMethod() {
        String html = groovyPageRenderer.render(view: '/email/someTemplateName')
    }
}

API - http://grails.org/doc/latest/api/grails/gsp/PageRenderer.html

More complete example - http://mrhaki.blogspot.com/2012/03/grails-goodness-render-gsp-views-and.html

like image 30
Dan Tanner Avatar answered Oct 03 '22 18:10

Dan Tanner