How to know programmatically if a view or a layout file exists in grails

坚强是说给别人听的谎言 提交于 2019-12-19 06:51:43

问题


I want to know programmatically if a view or a layout exists in grails.

I am thinking in obtain the absolutepath and ask for File.exists but I don't know how to obtain this path for every enviroment.

I had tried groovyPagesTemplateEngine.getUriWithinGrailsViews('a-view.gsp') without success.

Can you give me any pointer?

thanks in advance


回答1:


I see 2 possibilities

Search for view file

If you build a war file you will see that views are stored in WEB-INF/grails-app/views. You can search for that resource.

def uri = this.getClass().getResource("/grails-app/views/...").toURI()
if(new File(uri).exists()){...}

Use PathMatchingResourcePatternResolver

Find a inspiration in assertView method of GrailsUrlMappingsTestCase.

def patternResolver = new PathMatchingResourcePatternResolver()
def pathPattern = "grails-app/views/" + ((controller) ? "$controller/" : "") + "${view}.*"
if (!patternResolver.getResources(pathPattern)) {...}



回答2:


Since Grails 2.0, you can inject a GrailsConventionGroovyPageLocator:

GrailsConventionGroovyPageLocator groovyPageLocator

and call

groovyPageLocator.findViewByPath(...)
groovyPageLocator.findTemplateByPath(...)

to check if views or templates exist.




回答3:


Additionally to what amra said, you can also use grailsAttributes(see docs for GrailsApplicationAttributes). Quick example:

private templateExists(String name) {
    def template = grailsAttributes.getTemplateUri(name, request)
    def resource = grailsAttributes.pagesTemplateEngine
                                   .getResourceForUri(template)
    return resource && resource.file && resource.exists()
}

This example is of course for templates but as you can see from the docs, similar method exists for views too.



来源:https://stackoverflow.com/questions/3391949/how-to-know-programmatically-if-a-view-or-a-layout-file-exists-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!