Search code examples
grails

createLink in ApplicationTagLib from service


I am trying to learn about creating the link using createLink from ApplicationTagLib called from the service.

Grails : 3.2.8

Code :

def applicationTag = new ApplicationTagLib()

def abc = application.Tag.createLink(controller:"accomodate", action:"menu", id:4)

Error :

org.grails.taglib.GrailsTagException: Tag [createLink] does not exist. No corresponding tag library found.

I am very new to this version. I will be really thankful if you help me in finding out what sort of mistake is my code having.


Solution

  • try this:

    import grails.core.support.GrailsApplicationAware
    import grails.core.GrailsApplication
    import grails.web.mapping.LinkGenerator
       class MyService implements GrailsApplicationAware{
          GrailsApplication grailsApplication
          def config
          LinkGenerator grailsLinkGenerator
    
          def myMethod() {
    
              def url = hostname+grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: 'false')
        }
         void setGrailsApplication(GrailsApplication ga) {
            config = ga.config
        }
    }
    

    ...

    String hostname=grailsApplication.config.myApp?.hostName
            def url=hostname+grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: 'false')
    

    or

    def url=grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: true)
    

    ED2A If you must

    I have applicationTag lib working this way:

    import grails.util.Holders
    import org.grails.plugins.web.taglib.ApplicationTagLib
    
     class SomeService { 
    
     def g = Holders.grailsApplication.mainContext.getBean(ApplicationTagLib)
    
    
       def someMethod() {
           def aa = g.createLink('something')
       }
      }
    

    The problem with doing things this way is if you start hitting presentation layer references then you may get No thread-bound request found. Specially from quartz jobs and anything that is called outside of the scope of a real user. You can get around all of this using this example. But why go through all that when the grailsLinkGenerator example above won't hit any of the issues that may arise otherwise