首页 > 代码库 > Gradle Goodness: Parse Files with SimpleTemplateEngine in Copy Task

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.

view sourceprint?
00.version = ‘DEMO‘
01.group = ‘com.mrhaki‘
02. 
03.task copy(type: Copy) {
04.from ‘src/templates‘
05.into "$buildDir"
06.include ‘projectinfo.html.template‘
07.rename { file -> ‘projectinfo.html‘ }
08.expand(project: project, title: ‘ProjectInfo‘, generated: new Date())
09.}

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

view sourceprint?
00.<html>
01.<head>
02.<title>${title}</title>
03.</head>
04.<body>
05.<h1>${project.name}</h1>
06. 
07.<ul>
08.<% project.properties.findAll { k,v -> v instanceof String }.each { key, value -> %>
09.<li>$key = $value</li>
10.<% } %>
11.</ul>
12. 
13.<hr />
14.<p>Generated on ${generated.format(‘dd-MM-yyyy‘)}</p>
15.</body>
16.</html>

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

技术分享

Gradle Goodness: Parse Files with SimpleTemplateEngine in Copy Task