Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

groovy - Rendering HTML files in Grails

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??

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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"

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
  }
}

You can call this tag from a GSP using

<html:render file="/bar/foo.html"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...