Loading...

October 22, 2010

Gradle Goodness: Parse Files with SimpleTemplateEngine in Copy Task

With the copy task of Gradle we can copy files that are parsed by Groovy's SimpleTemplateEngine. This means we can expand properties in the source file and add Groovy code that is going to be executed. We must use the expand() method in the copy task where we can pass properties to be used in the source file.

version = 'DEMO'
group = 'com.mrhaki'

task copy(type: Copy) {
    from 'src/templates'
    into "$buildDir"
    include 'projectinfo.html.template'
    rename { file -> 'projectinfo.html' }
    expand(project: project, title: 'ProjectInfo', generated: new Date())
}

We define the following source file in src/templates/projectinfo.html.template:

<html>
    <head>
        <title>${title}</title>
    </head>
    <body>
        <h1>${project.name}</h1>

        <ul>
        <% project.properties.findAll { k,v -> v instanceof String }.each { key, value -> %>
            <li>$key = $value</li>
        <% } %>
        </ul>

        <hr />
        <p>Generated on ${generated.format('dd-MM-yyyy')}</p>
    </body>
</html>

When we run the copy task we get the following output: