So, a while back I was impressed by Rails routing. It was a nice little surprise which came out of left field to impress me: I love it when frameworks do that.
Grails just had its time — taglibs. Now, because of the pain of JSP tag libraries, I’ve avoided anything that sounded anything like UI taglibs. But, I was starting to repeat myself in views, and in such a way that partials seemed a bit hokey. This is where custom tags come in.
So, I sucked it up and checked out Grails taglibs. The limited documentation on the page scared the crap out of me, because I assumed I was going to get stuck and there’d be no help.
Turned out I didn’t need any. Nice.
The code that repeated looked like this:
<g:if test="${data.otherDobs}"> <g:link action="otherDobs" id="${id}"> Other Date(s) of Birth </g:link> </g:if> <g:else> </g:else>
The argument to “test”, the “action”, the “id”, and the text to display all varied.
After the taglib, it looks like this:
<g:moreData test="${data.otherDobs}" action="otherDobs" id="${id}"> Other Date(s) of Birth </g:moreData>
The taglib was just:
class MyAppTagLib { def moreData = { attr, body -> if(attr['test']) { out << link([action: attr['action'], id: attr['id']], { body() }) } else { out << ' ' } } }
Cute. For bonus points, I could have passed all the attrs except for ‘test’ down into link, but I decided against doing that right now. All the magic was freaking me out.
Related posts: