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

前提是你 提交于 2019-11-30 13:10:24

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)
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!