Render a template as string in a service in Grails 3 rest-api profile app

grails, grails3, spring

Solution

For Grails 3 app created with `web` profile, they can always use the `groovyPageRenderer` as given in the link Grails render view from service?.

And for the app created with `rest-api` profile, they just need to add the following in `build.gradle` under `dependencies` block:

compile "org.grails:grails-plugin-gsp:3.2.1"

And the above link will also work as is.

Just for the sake of description, inject the bean and use the `render` method:

PageRenderer groovyPageRenderer

def someMethod() {
    println groovyPageRenderer.render(template: "/email-templates/signup", model: [foo: "bar"])
}

Problem

I've created a Grails `3.2.1` app with `rest-api` profile and want to render a GSP template as a String. For this I first added, `apply plugin:"org.grails.grails-gsp"` in `build.gradle` then based on the code of ResponseRenderer, I tried following to render my GSP template as: ``` def viewResolver = applicationContext.getBean(CompositeViewResolver.BEAN_NAME, CompositeViewResolver) View view = viewResolver.resolveView("/email-templates/signup", null) ``` But the `view` object is always `null`. Then I tried the following as well without success: ``` [ViewResolverComposite, GroovyMarkupViewResolver, GenericGroovyTemplateViewResolver].each { def viewResolver = applicationContext.getBean(it) View view = viewResolver.resolveViewName("/email-templates/signup", null) println view?.dump() } ``` My template is located at `grails-app/views/emails-templates/_signup.gsp`. In Grails 2, it was quite simple by injecting `groovyPageRenderer` bean of type PageRenderer but I think, that bean and class is no longer used in Grails 3.

Original source