2010-01-18 86 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("") 
相關問題