views:

422

answers:

2

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?

+4  A: 

My advice would be to do this in the controller. Service should have reusable logic and not depend on a view template, leave that work to the controller. Use the service to get the data you need to pass to the template, but leave the work of interacting with the template to the controller.

John Wagenleitner
+7  A: 

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.

Stefan
with great power comes great responsibility! becareful when doing things like this - make sure you know the reasoning behind rendering gsp in a service before doing it :)
Chii
My intent was to render a template and then return with with JSON so the resulting HTML could be inserted. I was going to encapsulate the logic in a service, but found that just returning the JSON manually in each controller works just as well, and g.render is already available. Thanks everyone for your input.
aasukisuki