# HG changeset patch # User Dirk Olmes # Date 1623854417 -7200 # Node ID 712e2e9cf8b1546b9c0910cc615f871cccbc3fea # Parent 3cdb6b87125b5e074b94bc70bdce3718df12e181 new blog post diff -r 3cdb6b87125b -r 712e2e9cf8b1 content/Maven/gmaven-string-template-engine.md --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/content/Maven/gmaven-string-template-engine.md Wed Jun 16 16:40:17 2021 +0200 @@ -0,0 +1,46 @@ +Title: Quick templating with gmaven and GStringTemplateEngine +Date: 2020-06-16 +Lang: en + +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. + +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. + +As it turns out groovy comes with a templating engine built in: `groovy.text.GStringTemplateEngine`. Using it is fairly straightforward from Maven: + + :::xml + .... + + org.codehaus.gmaven + groovy-maven-plugin + 2.1.1 + + + generate-resources + + execute + + + ${project.basedir}/templateGenerator.groovy + + + + + +The `templateGenerator.groovy` Script is only a few lines long: + + :::java + import java.io.File + import groovy.text.GStringTemplateEngine + + def templateFile = "${project.basedir}/template.file" as File + def outputFile = "${project.build.directory}/dependencies.html" as File + outputFile.newWriter("UTF-8").withCloseable { writer -> + def engine = new GStringTemplateEngine() + def replacements = [ dependencies: project.dependencies ] + engine.createTemplate(templateFile).make(replacements).writeTo(writer) + } + +The template file can contain any syntax that the [GStringTemplate](https://docs.groovy-lang.org/latest/html/api/groovy/text/GStringTemplateEngine.html) supports. + +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.