Geertjan's Blog

  • November 4, 2007

Groovy Template (Part 1)

Geertjan Wielenga
Product Manager
For a while I've been trying to figure out how to use Groovy templates to work with HTML files. The scenario is typical: you have one set of HTML files but you want to use them in different contexts. For example, in one context you want the files to have a copyright notice, while in another you don't. Rather than maintaining two separate sets of HTML files (and rather than dealing with it manually, by cutting and copying and pasting and so on), you'd like to run a script that replaces a variable with the relevant content for the context in question.

So, now, my HTML files all have this string right above the closing BODY tag:


Then, using the script below, all HTML files in a folder are found, each of them is opened by Groovy, a binding is performed from ${footer} to some real content (e.g., "Copyright, Blafoo Co., 1997"), and then the result is written to a new file, which is (in this case) in the same folder as the original. So, hurray, that's the end of multiple copies of the same source, because I can control the source via a Groovy template!

And here is all the code:

void main(){
//We want to deal with files that end in '.html':
def p = ~/.\*html/
//We specify a directory and find each file that matches '.html' as an extension:
new File( '/home/geertjan/myProjects/' ).eachFileMatch(p) {
//For each file...
f ->
//...the following happens:
//We define 'text', which contains the file's text:
def text = f.text
//We specify that every ${footer} will be replaced by "Footer of " + file name,
: //which, in real life, would be something like "Copyright, FooBla Co., 1997":
def binding = ["footer":"Footer of " + f.name]
//We define our template engine:
def engine = new SimpleTemplateEngine()
//We define a template, which we use to swap the ${footer} string
//with "Footer of " + file name:
def template = engine.createTemplate(text).make(binding)
//We create an output file:
def outFile = new File('/home/geertjan/myProjects/new' + f.name)
//We write our new string to it:

Of course, I could put multiple different variables in my HTML files and they'd all be handled by this script. This is really cool and powerful stuff.

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.