How To Call A Taglib As A Function In A Domain Class

后端 未结 2 1724
予麋鹿
予麋鹿 2021-01-02 07:30

I need to call the Static Resources Plugin (http://www.grails.org/Static+Resources+Plugin) from my domain class.

This works perfectly in a controller:



        
2条回答
  •  走了就别回头了
    2021-01-02 08:08

    I encountered this problem a while ago for an app I was working on. What I ended up doing was putting a call to the tag in a service method:

    class MyService {
       def grailsApplication //autowired by spring
    
       def methodThatUsesATag(identifier, originalFileName) {
          //This is the default grails tag library
          def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
    
          g.resourceLinkTo(dir:"docs/${identifier}",file:originalFileName)
       }
    }
    

    Then in my domain class, I could get to the service via spring autowiring as well:

    class MyDomain {
        String originalFileName
        def myService  //autowired
    
        static transients = ['myService'] //Necessary so that GORM doesn't try to persist the service instance.
    
        //You can create a method at this point that uses your
        //service to return what you need from the domain instance.
        def myMethod() {
           myService.methodThatUsesATag(id, originalFileName)
        }
    }
    

提交回复
热议问题