【发布时间】:2021-01-26 15:06:41
【问题描述】:
当要包含的模板不在views文件夹下时,如何在GSP文件中包含外部GSP或模板?
【问题讨论】:
标签: grails
当要包含的模板不在views文件夹下时,如何在GSP文件中包含外部GSP或模板?
【问题讨论】:
标签: grails
是的,您可以轻松做到这一点。给你:
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>
【讨论】:
我知道我迟到了,但是当我们尝试将报表视图放在视图文件夹之外时遇到了这个问题。
我们无法使用上述方法,因为我们正在运行一个 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"
}
【讨论】: