tags:

views:

39

answers:

1

I need to test whether a resource file (an image, for instance) exists and if not, I will display another image. My GSP view code looks like:

<% if (resExists(dir: "images", file:"img.jpg")) {%>
  <img src="${g.resource(dir:'images',file: 'img.jpg')}">
<% else { %>
  <img src="${g.resource(dir:'images',file: 'noimg.jpg')}">
<%}%>

How can I test for a file existence in Grails? What is the code of the method boolean resExists()

+1  A: 

I found out the answer:

def resExists(resPath)  {
    def resFile = grailsApplication.parentContext.getResource(resPath)
    resFile?.exists()
}

or

def resExists(resPath)  {
    def resFile = request.servletContext.getResource(resPath)
    resPath
}

And you call it with resExists('images/img.jpg')

fabien7474
Good job. You might try to make that into a custom tag for your application. See http://www.grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.2.2%20GSP%20Tags
Matt Lachman