GSP software rendering

Suppose I have a gsp fragment stored in my database. How to programmatically combine it with a data model to create a row.

+4
source share
3 answers

The context application of any Grails application contains a bean named

groovyPagesTemplateEngine 

By default, this is an instance of GroovyPagesTemplateEngine . So you can use this code in your controller or service:

 class MyService/MyController { def groovyPagesTemplateEngine String renderGSPToString(String uri, Map model) { groovyPagesTemplateEngine.createTemplate(uri).make(model).toString() } } 

NB: this snippet really is not inferred from running the code, it should just clarify the idea.

+4
source

I found a DIRTY (but working) way to render complex gsps offline using groovyPageRenderer with a replaced script source. In this case, you have access to the entire gsp syntax, including g:if , etc.

First define two dummy classes:

 class StringPageLocator extends GrailsConventionGroovyPageLocator { GroovyPageScriptSource findViewByPath(String content) { return new StringScriptSource(content) } } class StringScriptSource implements GroovyPageScriptSource{ String content public StringScriptSource(String content) { this.content=content } @Override String suggestedClassName() { "DummyName" } @Override boolean isPublic() { true } @Override String getScriptAsString() { return content } @Override boolean isModified() { true } @Override String getURI() { "DummyURI" } } 

And then you can use it as such:

 def groovyPageLocator // Injected automaticaly to service/controller etc... groovyPageRenderer.groovyPageLocator=new StringPageLocator() String output=groovyPageRenderer.render( view:'Hello2 ${user} <g:if test="${test}">TRUE!!!</g:if>', model:[user:'test user2',test:true] 

)

0
source

You can create a controller method that will do what you want. Then you will have an HTTP api to accomplish what you want. The controller method template will have a <g:render> , appropriately parameterized.

0
source

Source: https://habr.com/ru/post/1307223/


All Articles