在 Grails 中渲染 HTML 文件 [英] Rendering HTML files in Grails
问题描述
我环顾四周,但找不到在 Grails 中简单地包含或呈现 *.html 文件的方法.我的应用程序需要 g.render
或
模板,这些模板以 html 文件形式提供.为此,正如我们所知,必须将 html 文件转换为 _foo.gsp
文件才能进行渲染.我很惊讶为什么没有对 html 的直接支持,或者有吗??
I've looked around but could not find a way of simply including or rendering *.html files in Grails. My application needs to g.render
or <g:render>
templates which are delivered as html files. For this, as we know, html files have to be converted to _foo.gsp
files in order to get rendered. I am totally surprised as to why isn't there a direct support for html or is there one??
谢谢!
推荐答案
一个明显的选择是简单地将 HTML 文件从 foo.html
重命名为 _foo.gsp
和然后使用
.然而,这太明显了,我相信你已经想到了.
One obvious option is to simply rename your HTML files from foo.html
to _foo.gsp
and then use <render template="foo">
. However this is so obvious that I'm sure you've already thought of it.
如果你只是想从控制器中渲染一个 HTML 文件,你可以使用 render
controller 方法的 text
参数>
If you simply want to render a HTML file from within a controller you can use the text
parameter of the render
controller method
def htmlContent = new File('/bar/foo.html').text
render text: htmlContent, contentType:"text/html", encoding:"UTF-8"
如果你想在 .gsp 中做同样的事情,你可以写一个标签.类似以下内容(未经测试)应该可以工作:
If you want to do the same thing from within a .gsp, you could write a tag. Something like the following (untested) should work:
import org.springframework.web.context.request.RequestContextHolder
class HtmlTagLib {
static namespace = 'html'
def render = {attrs ->
def filePath = attrs.file
if (!file) {
throwTagError("'file' attribute must be provided")
}
def htmlContent = new File(filePath).text
out << htmlContent
}
}
您可以使用
<html:render file="/bar/foo.html"/>
这篇关于在 Grails 中渲染 HTML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!