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

后端 未结 2 1727
予麋鹿
予麋鹿 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)
        }
    }
    
    0 讨论(0)
  • 2021-01-02 08:12

    Most taglibs rely on data from the controller so it's often not possible to reuse them while others concern view logic so often it's not something you would want to put in a domain class.

    That said, I'm sure you have your reasons so maybe the source of the taglib will help:

    class ResourceTagLib  {
    
        def externalResourceServerService
    
        def resourceLinkTo = { attrs ->
            out << externalResourceServerService.uri
            out << '/'
            if(attrs['dir']) {
                out << "${attrs['dir']}/"
            }
            if(attrs['file']) {
                out << "${attrs['file']}"
            }
        }
    }
    

    ie inject the externalResourceServerService into your domain class and the rest should be simple.

    0 讨论(0)
提交回复
热议问题