Grails包含来自外部位置的模板

时间:2015-05-14 22:21:25

标签: grails

当要包含的模板不在views文件夹下时,如何在GSP文件中包含外部GSP或模板?

2 个答案:

答案 0 :(得分:3)

是的,你可以很容易地做到这一点。你走了:

import grails.gsp.PageRenderer

class MyLib {

    static namespace = "foo"
    static defaultEncodeAs = "raw"

    PageRenderer groovyPageRenderer

    def externalTemplate = { attrs, body ->
        String externalFilePath = attrs.externalPath

        /*
         * Put content of that external template to a file inside grails-app/views folder
         * with a temporary unique name appended by current timestamp
         */
        String temporaryFileName = "_external-" + System.currentTimeMillis() + ".gsp"

        File temporaryFile = new File("./grails-app/views/temp/$temporaryFileName")

        /*
         * Copy content of external file path to the temporary file in views folder.
         * This is required since the groovyPageRenderer can compile any GSP located inside
         * the views folder.
         */
        temporaryFile.text << new File(externalFilePath).text

        /*
         * Now compile the content of the external GSP code and render it
         */
        out << groovyPageRenderer.render([template: "/temp/$temporaryFileName", model: attrs.model])

        // Delete the file finally
        temporaryFile.delete()
    }
}

现在,在您想要包含外部GSP的实际GSP中,您可以这样写:

<body>
    <foo:externalTemplate externalPath="/home/user/anyExternalFile.gsp" model="${[status: 1}" />
</body>

答案 1 :(得分:0)

我知道我迟到了这个回复,但是当我们尝试将报表视图放在视图文件夹之外时遇到了这个问题。

我们无法使用上述方法,因为我们正在运行一个 jar 包,并且无法在 views 文件夹中创建文件。

这是 Grails 4 上的解决方案

第一次注入

def groovyPagesTemplateEngine
def groovyPageLayoutFinder

然后在您的控制器中

File externalFile = new File("/path/to/file.gsp")

if(externalFile && externalFile.exists()){
     GroovyPageView groovyPageView = new GroovyPageView()
     LinkedHashMap model = [:]
     Template template = groovyPagesTemplateEngine.createTemplate(externalFile.text, externalFileName)

     groovyPageView.setServletContext(getServletContext())
     groovyPageView.setTemplate(template)
     groovyPageView.setApplicationContext(getApplicationContext())
     groovyPageView.setTemplateEngine(groovyPagesTemplateEngine)
     groovyPageView.afterPropertiesSet()
     request.setAttribute GrailsLayoutDecoratorMapper.LAYOUT_ATTRIBUTE, null
     GrailsLayoutView grailsLayoutView = new GrailsLayoutView(groovyPageLayoutFinder, groovyPageView)
     grailsLayoutView.render model, webRequest.getCurrentRequest(), webRequest.getResponse()
     webRequest.renderView = false
     return
}
else {
     // something that shows error
     render "not found"
}