How to add new tags to TagLib?

Suppose I have the following configuration in a conf/InjectionConfig.groovy file:

 x { a = { attrs, body -> out << "hello" } b = { attrs, body -> out << "goodbye" } } 

and that I have a simple taglib such as

 class XTagLib { static namespace = "x" } 

What I want to do is that when I type <x:a /> for any of my views, it prints hello . I already tried to insert these taglib metaclasses as a property and method, but none of them work. As an example, here is basically what I'm doing right now in the service:

 public void afterPropertiesSet() throws Exception { GroovyClassLoader classLoader = new GroovyClassLoader(getClass().classLoader) def slurper = new ConfigSlurper(GrailsUtil.environment) ConfigObject xConfig try { xConfig = slurper.parse(classLoader.loadClass('InjectionConfig')) } catch (e) { e.printStackTrace() } xConfig.x.each({ if ( !XTagLib.metaClass.hasMetaProperty(it.key) ) { XTagLib.metaClass.registerBeanProperty(it.key, { args -> def attrs = args[0], body = args[1] it.value.call(attrs, body) } } }) } 

Am I just doing it wrong or is it possible now?

+4
source share
2 answers

Well it

  def shell = new GroovyShell() // or get a GroovyClassLoader Class yTagLibClass = shell.evaluate("class YTagLib { static namespace = 'x' }; return YTagLib") yTagLibClass.metaClass.a = { attrs, body -> delegate.out << 'blabla' } grailsApplication.addArtefact(TagLibArtefactHandler.TYPE, yTagLibClass) 

<x: a / "> almost worked for me - I registered the tag, except that it didnโ€™t output anything. You still need to enable the out closure for the taglib out property from Grails.

I do not see any good ways to do this, since there is no access to instance variables, and out is an instance variable. See Grails Source, JspInvokeGrailsTagLibTag.doStartTagInternal () - you can find a way.

EDIT : I added the delegate. prefix delegate. which should resolve the out property of the target. Now I think I deserve recognition :)

+2
source

What I want to do is when I print to any of my views, itโ€™s print hi

I think there is an alternative way to do what you intend to: combine the template and tagLib. First create a template, then add it to your TagLib (without complicated configuration).

In my opinion, this is easier than your approach.

Please take a look at this tutorial: http://jan-so.blogspot.com/2008/02/example-of-template-and-taglib-with.html

+1
source

All Articles