6

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

user2427
  • 7,842
  • 19
  • 61
  • 71

3 Answers3

18

Since Grails 2.0, you can inject a GrailsConventionGroovyPageLocator:

GrailsConventionGroovyPageLocator groovyPageLocator

and call

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

to check if views or templates exist.

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
  • 2
    This also works quite nicely... `groovyPageLocator.findTemplate("/same/as/render/template")` (If you have a template file at `/grails-app/views/same/as/render/_template.gsp`) – chim Sep 05 '12 at 09:11
  • I know this was ages ago, but I get nothing from this. It returns null every time, event when I manually setGrailsApplication() – user2782001 Apr 12 '19 at 00:11
  • 2
    In recent Grails versions (perhaps since GSP became a plugin) the exact type of the page locator has changed. Cheat by omitting the class when injecting it, like `def groovyPageLocator` – sodastream Jun 06 '20 at 07:39
  • It works in Grails 3 declaring like this: `def groovyPageLocator` – IgniteCoders Jun 12 '20 at 02:39
4

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.

Esko
  • 29,022
  • 11
  • 55
  • 82
3

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)) {...}
amra
  • 16,125
  • 7
  • 50
  • 47