Friday, February 8, 2019

GRAILS : Rendering Groovy GSP Code From A String | Grails – Rendering a Template from a String | Render Grails template from external source




package com.pkm.utils

import grails.util.Holders
import groovy.text.Template
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
import org.springframework.core.io.ByteArrayResource
import org.springframework.web.context.request.RequestContextHolder

/**
 * Created by pritom on 29/11/2017.
 */
class InvoicePdfUtils extends UtilsBase {
    static def test() {
        GroovyPagesTemplateEngine engine = Holders.applicationContext.getBean(GroovyPagesTemplateEngine)
        StringWriter stringWriter = new StringWriter()

        String content = "CONTENT-\${a}--\${b.none?.none ?: 'None'}-MINE-XXX " +
                "<ui:serverURL/> <g:if test='true'>True</g:if> HERE??? YES ME IS HERE, ".toString()
        Map model = [a: '10', b: [:]]

        String pageName = engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request) // /grails/test.dispatch
        Template template = engine.createTemplate(new ByteArrayResource(content.getBytes("UTF-8"), pageName), pageName, true)
        Writable renderedTemplate = template.make(model)
        renderedTemplate.writeTo(stringWriter)

        println("Request-path=${engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request)}")
        println(stringWriter.toString())
    }
}


This code block will take input from yourself and then parse as a GSP parser and return output as String.

https://little418.com/2009/11/rendering-groovy-gsp-code-from-a-string.html

No comments:

Post a Comment