Grails and the Google Plus One button
One of the cool things about writing your own blog software is getting to geek out on new features. It doesn't come without it's own set of pains at times. There is no one to blame or look at to fix it. It's just you. Whilst trying to add a Google +1 button, I came across an interesting bug due to assumptions that Grails makes.
The code on Google's website says you can add a +1 button to your pages with the following code.
<script type="text/javascript" src="http://apis.google.com/js/plusone.js"></script>
<!-- Place this tag where you want the +1 button to render -->
<g:plusone></g:plusone>
When you put <g:plusone> in a page, at the time when it inspects the page with SiteMesh, it expects a taglib with the g prefix to be one that it or the user has defined. The above code in a GSP is a bag of fail.
Next I tried some quick JQuery:
$("#div").append("<g:plusone></g:plusone")
I figured that even in the head, the script would get executed late enough to not get the SiteMesh errors I got with the first attempt. WRONG. Next I decided to be spiffy and create a simple pass-through taglib. While it worked and was able to seamlessly match the Google-provided code, it isn't optimal because one would have to reconstruct the attributes list just for this pass-through step and it is prone to breakage. Totally possible in a one or two liner but a bit too much.
class GooglePlusOneTagLib {
def plusone = { attrs, body ->
out << '<g:plusone ${attrs}></g:plusone>'
}
def plusoneScript = { attrs, body ->
out << '<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>'
}
}
In their documentation, I later found that you could create the widgets explicitly using dives and I did that.
From start to finish, it only took about 20 minutes but it reminds me of a talk my friend Colin Harrington gave at GR8 USA yesterday titled "There and back again: a story of a simple HTTP request".
The big takeaway is that Grails does a lot for you and makes life easier but if you don't have any idea about the sequence of operations, it's easy to get yourself in trouble.