Wednesday, November 16, 2011

How to display Static HTML Pages from Grails

They must be an easy way to do this but after a lot of Googling and some failures I used the following approach.

Store the HTML file in the web-app/WEB-INF folder of your grails application in a suitable subdirectory.

Where you wish to provide a link in a GSP page add the following, changing the file and dir strings as required:

 <g:link controller="ServeStatic" action="index"
params="[file:'disclaimer.html',dir:'/WEB-INF/FutureLetters/legal/']" >
Our WebSite Disclaimer</g:link>

Create the Grails Controller to render the file:

package com.yourdomain

import org.codehaus.groovy.grails.commons.ApplicationHolder

class ServeStaticController {

        def index(  ) {
       
        def file = params.file
        def dir = params.dir
       
        File layoutFolder = ApplicationHolder.application.parentContext.getResource("${dir}").file
       
        def absolutePath = layoutFolder.absolutePath
        def fileName = "${absolutePath}/${file}"
       
        File newLayoutFile = new File(fileName)
        def is = newLayoutFile.newInputStream()

        def String exportTemplate = is.text
       
        render exportTemplate
    }
}