Mercurial > hg > Blog
comparison content/Maven/gmaven-string-template-engine.md @ 107:712e2e9cf8b1
new blog post
| author | Dirk Olmes <dirk.olmes@codedo.de> |
|---|---|
| date | Wed, 16 Jun 2021 16:40:17 +0200 |
| parents | |
| children | ee048ed76ea1 |
comparison
equal
deleted
inserted
replaced
| 106:3cdb6b87125b | 107:712e2e9cf8b1 |
|---|---|
| 1 Title: Quick templating with gmaven and GStringTemplateEngine | |
| 2 Date: 2020-06-16 | |
| 3 Lang: en | |
| 4 | |
| 5 At work I have come across the requirement to generate some files based on the info in a `pom.xml`. Maven's [resource filtering](https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html) feature would be the first thing that comes to mind but unfortunately it's not powerful enough for my use case. I had to generate a file based on the dependencies that are referenced in the project. | |
| 6 | |
| 7 A bit of googling found all kinds of outdated or unsupported maven plugins but nothing that would fit my use case directly. Finally I gave up and started to hack something together in groovy. | |
| 8 | |
| 9 As it turns out groovy comes with a templating engine built in: `groovy.text.GStringTemplateEngine`. Using it is fairly straightforward from Maven: | |
| 10 | |
| 11 :::xml | |
| 12 .... | |
| 13 <plugin> | |
| 14 <groupId>org.codehaus.gmaven</groupId> | |
| 15 <artifactId>groovy-maven-plugin</artifactId> | |
| 16 <version>2.1.1</version> | |
| 17 <executions> | |
| 18 <execution> | |
| 19 <phase>generate-resources</phase> | |
| 20 <goals> | |
| 21 <goal>execute</goal> | |
| 22 </goals> | |
| 23 <configuration> | |
| 24 <source>${project.basedir}/templateGenerator.groovy</source> | |
| 25 </configuration> | |
| 26 </execution> | |
| 27 </executions> | |
| 28 </plugin> | |
| 29 | |
| 30 The `templateGenerator.groovy` Script is only a few lines long: | |
| 31 | |
| 32 :::java | |
| 33 import java.io.File | |
| 34 import groovy.text.GStringTemplateEngine | |
| 35 | |
| 36 def templateFile = "${project.basedir}/template.file" as File | |
| 37 def outputFile = "${project.build.directory}/dependencies.html" as File | |
| 38 outputFile.newWriter("UTF-8").withCloseable { writer -> | |
| 39 def engine = new GStringTemplateEngine() | |
| 40 def replacements = [ dependencies: project.dependencies ] | |
| 41 engine.createTemplate(templateFile).make(replacements).writeTo(writer) | |
| 42 } | |
| 43 | |
| 44 The template file can contain any syntax that the [GStringTemplate](https://docs.groovy-lang.org/latest/html/api/groovy/text/GStringTemplateEngine.html) supports. | |
| 45 | |
| 46 IMHO this approach supports the best of both worlds: with only a little groovy scripting magic you get the maximum flexibility of a templating engine that has access to all the internals of your project. |
