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)

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Barney's Gravatar For most of the places I generate markup with Groovy, I just skip the builder and use the """...""" string format for everything. Especially for longish-but-simple HTML, I find it far easier to read than the builder syntax, and since they're GStrings, you can do ${} interpolation for dynamic bits.
# Posted By Barney | 2/12/09 6:28 PM
Raymond Camden's Gravatar On reflection, I probably should have too. Although I really find the builder stuff cool.

Another tip - how do you include html entities in builders? Use yield.unEscaped:

th {html.yieldUnescaped "&nbsp;" }
# Posted By Raymond Camden | 2/12/09 6:38 PM
Dan Vega's Gravatar Groovy builders simply rock!
# Posted By Dan Vega | 2/19/09 10:59 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002. Contact Blog Owner