Generating Grails static resource link manually

22 / Oct / 2015 by Salil 0 comments

In case you are using Grails resources plugin and at some point you need to generate the static resource link in some service or ordinary ‘src’ class – following is a quick code that can help you getting the resources link/URL (by using resources tag lib only). The good part is that it’s not a hard-coded URL, so it will follow all the standards/settings configured around the Grails resources-plugin.

def grailsApplication
String getStaticResourceLink(String uri){
            def resourceTagLib = grailsApplication.mainContext.getBean("org.grails.plugin.resource.ResourceTagLib")
            def rLinkResource = resourceTagLib ? resourceTagLib.resolveLinkUriToUriAndResource(uri: uri): null
                uri = rLinkResource.uri
        return uri

Usually, resources plugin automatically renders the URLs in an application. But this was a very special requirement where I was required to generate the link manually. Another condition was to follow all the resources-plugin’s settings because it does a lot of work before generating the (dynamic/accurate/relevant) links. So this worked very well – even for the CDN configurations.
The only thing you need to take care is to pass the correct “uri” otherwise (if resource not found at the given location/uri) you may get a broken link.

I hope it will help someone. :-)


Leave a comment -