Saturday, June 16, 2018

Grails on Groovy > Grails 2 > How to know programmatically if a view or a layout file exists in grails | Check if view or layout file exists

I want to know programmatically if a view or a layout exists in grails.
Since Grails 2.0, you can inject a GrailsConventionGroovyPageLocator:
package com.pkm

import org.codehaus.groovy.grails.web.pages.discovery.GrailsConventionGroovyPageLocator

class HomeController {
    GrailsConventionGroovyPageLocator groovyPageLocator

    def index() {
        println(groovyPageLocator.findView("myView"))
        println(groovyPageLocator.findViewByPath("/home/myView"))
        println(groovyPageLocator.findTemplate("myTemplate"))
        println(groovyPageLocator.findTemplateByPath("/home/myTemplate"))
        render(text: "Done")
    }
}
Will output like below, it no view found, null return.
URL [file:C:/Grails-project-path/grails-app/views/home/myView.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/myView.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/_myTemplate.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/_myTemplate.gsp]

No comments:

Post a Comment