Groovy JavaScript
Many moons ago I blogged on how you can use Groovy to generate HTML files. I'm not doing this a lot at Broadchoice, only for a few administration type pages, but I had to work within this framework again this morning and ran into a little issue with JavaScript. I wanted to add a bit of jQuery to my page. Should be simple enough, right? My HTML document had an existing head that looked like this:
head {
title 'TPS Reports'
}
This generates:
<head>
<title>TPS Reports</title>
</head>
So adding jQuery in should be as simple as this:
head {
title 'TSP Reports'
script(type:'text/javascript',src:'js/jquery.js')
}
Right? Unfortunately, it isn't quite that easy. Sure, this works and generates out what you expect:
<script type='text/javascript' src='js/jquery.js' />
But notice the self-closing script tag? This doesn't work in some browsers. I thought perhaps it was just IE, but it didn't work in Firefox. Safari had no problem with it. (And I'd love to hear a good reason on why a self-closing script tag doesn't work. Seems like a bug to me!)
Unfortunately, I couldn't figure a way to tell Groovy's HTML Builder to include a 'real' closing tag as opposed to a self-closing tag. I then figured out this simple hack:
script(type:"text/javascript",src:'js/jquery.js',' ')
Notice the last unnamed argument? This will be used as the content for the script tag. You end up with:
<script type='text/javascript' src='js/jquery.js'> </script>
Which works just fine in Firefox and Safari. Silly, but effective. One more quick tip, although it's kind of obvious. I wasn't quite sure how I was going to write my JavaScript code since everything has to be formatted just right inside the builder. Then I remembered that I could simply provide the code as an argument:
def code = """
console.log('yep, Im running');
"""
html.html{
head {
title 'Space/Feed Actity Report'
script(type:"text/javascript",src:'js/jquery.js',' ')
script(type:"text/javascript",code)

Another tip - how do you include html entities in builders? Use yield.unEscaped:
th {html.yieldUnescaped " " }