我环顾四周,但找不到在 Grails 中简单地包含或呈现 *.html 文件的方法。我的应用程序需要g.render
或<g:render>
以 html 文件形式提供的模板。为此,正如我们所知,必须将 html 文件转换为_foo.gsp
文件才能进行渲染。我很惊讶为什么没有直接支持 html 或者有一个?
谢谢!
一个明显的选择是简单地将您的 HTML 文件从foo.html
to重命名_foo.gsp
,然后使用<render template="foo">
. 然而,这很明显,我相信你已经想到了。
如果您只是想从控制器中呈现 HTML 文件,您可以使用控制器方法text
的参数render
def htmlContent = new File('/bar/foo.html').text
render text: htmlContent, contentType:"text/html", encoding:"UTF-8"
如果你想在 .gsp 中做同样的事情,你可以写一个标签。类似以下(未经测试)的东西应该可以工作:
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
}
}
您可以使用 GSP 从 GSP 调用此标签
<html:render file="/bar/foo.html"/>
你想要完成什么?
从控制器渲染 html?在这种情况下,您所要做的就是将用户重定向到您控制的文件。
redirect(uri:"/html/my.html")
使用 html 文件而不是 gsp 模板文件?问题是,Grails 是一个“约定优于配置”的平台,这意味着您必须以“Grails 方式”做一些事情。这些文件需要 _ 和 the.gsp
但名称可以是任何您喜欢的名称,即使您使用与控制器相同的名称会更容易。您从中获得的知识是,每个了解 grails 并进入您的项目的开发人员都将了解事物是如何联系在一起的,这将帮助他们快速入门。
一点点修复了唐的例子,对我来说很好
导入 org.apache.commons.io.IOUtils
class HtmlTagLib {
static namespace = 'html'
def render = {attrs ->
def filePath = attrs.file
if (!filePath) {
throwTagError("'file' attribute must be provided")
}
IOUtils.copy(request.servletContext.getResourceAsStream(filePath), out);
}
}
我想编写托管在 grails 应用程序(v2.4.4)中的静态 html/ajax 页面,但使用控制器进行 url 重写。我可以通过将文件移动到 web-app/ 来实现这一点(为了便于参考),并且只需使用带有 'file' 和 'contentType' 参数的 render() 方法,例如:
// My controller action
def tmp() {
render file: 'web-app/tmp.html', contentType: 'text/html'
}
注意:我只使用run-app尝试过这个,还没有打包战争并部署到tomcat。
文档: http: //grails.github.io/grails-doc/2.4.4/ref/Controllers/render.html
Closure include = { attr ->
out << Holders.getServletContext().getResource(attr.file).getContent();
}
它与您的 grails 主应用程序的 web-app 文件夹相关
我能够使用@momo 的方法来允许包含用于 grails 渲染插件的外部文件,其中网络路径会在更高的环境中变得拙劣 - 我的最终结果如下:
def includeFile = { attr ->
URL resource = Holders.getServletContext().getResource(attr.file)
InputStream content = resource.getContent()
String text = content?.text
log.info "includeFile($attr) - resource: $resource, content.text.size(): ${text?.size()}"
out << text
}