2010-01-18 85 views
0

我需要测试资源文件(例如图像)是否存在,如果不存在,我将显示另一个图像。 我GSP视图代码如下所示:如何在运行时检查资源文件是否存在[grails]?

<% 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')}"> 
<%}%> 

我如何测试Grails中一个文件是否存在?什么是方法boolean resExists()

回答

1

我找到了答案的代码:

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

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

而你把它与resExists('images/img.jpg')

+0

干得好。您可以尝试将其制作为应用程序的自定义标签。请参阅http://www.grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.2.2%20GSP%20Tags – 2010-01-19 14:51:24

1

以上回答没有为工作我从一个插件中使用,打包成一场生产战。我现在使用以下命令:

GrailsConventionGroovyPageLocator groovyPageLocator 

def resExists(resPath) { 
    def resource = groovyPageLocator.findTemplateByPath(resPath) 
    resource 
} 
1

我已经做了在GSP如下:

<g:set var="flag" value="${new File(grailsApplication.mainContext.servletContext.getRealPath("images/sgs-geosol/sign/${sec.username()}.gif")).exists()}"></g:set> 

<g:if test="${flag}"> 

</g:if> 

下面的代码返回的Grails应用程序的实际路径:

grailsApplication.mainContext.servletContext.getRealPath("") 
相关问题