简体   繁体   English

GSP以编程方式呈现

[英]GSP rendering programmatically

Suppose I have a gsp snippet stored in my database. 假设我的数据库中存储了一个gsp片段。 How do I programmatically merge it with a data model to produce a string. 如何以编程方式将其与数据模型合并以生成字符串。

The applicationContext of any Grails app contains a bean named 任何Grails应用程序的applicationContext都包含一个名为的bean

groovyPagesTemplateEngine

By default this is a instance of GroovyPagesTemplateEngine . 默认情况下,这是GroovyPagesTemplateEngine的一个实例。 So you might use code like this 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 is not really taken from running code, it should just clarify the idea. 注意:这段代码并非真正从运行代码中获取,它应该只是澄清这个想法。

I found a DIRTY (but working) way of rendering complex gsps offline using groovyPageRenderer with substituted scriptsource. 我找到了一种使用groovyPageRenderer和替换的scriptsource渲染复杂gsps的DIRTY(但工作)方法。 In that case you have access to all gsp syntax including g:if etc.. 在这种情况下,您可以访问所有gsp语法,包括g:if等。

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]

)

You can make a controller method that does what you want. 您可以创建一个执行所需操作的控制器方法。 Then you will have an HTTP api to accomplish what you want. 然后你将有一个HTTP API来完成你想要的。 The controller method's template will have a <g:render> tag, appropriately parameterized. 控制器方法的模板将具有<g:render>标记,并进行适当的参数化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM