1

My requirement is to create a template engine to support a looping in it.

The final template should look something like this:

#cat output.template 
env:
  - name : param1 
    value : 1
  - name : param2 
    value : 2

I have pseudo code to explain my requirement

def f = new File('output.template')
def engine = new groovy.text.GStringTemplateEngine()

def mapping = [
    [ name : "param1",
      value : "1"],
    [ name : "param2",
      value : "2" ]
] // This mapping can consists of a multiple key value pairs.

def Template = engine.createTemplate(f).make(mapping) 

println "${Template}"

Can someone help me how to achieve this requirement of looping inside the templates and how should I modify my template?

*UPDATE : All the solutions provided by tim_yates or by Eduardo Melzer has resulted in following output with extra blank lines at the end of template. What could be the reason for that?* Are the solution providers not able to see this behavior or the issue is my system only?.

# groovy loop_template.groovy 
env:
  - name: param1
    value : 1 
  - name: param2
    value : 2 


root@instance-1:
Here_2_learn
  • 5,013
  • 15
  • 50
  • 68

1 Answers1

2

Change your template file to look like this:

#cat output.template
env:<% mapping.eachWithIndex { v, i -> %>
  - name : ${v.name}
    value : ${v.value}<% } %>

As you can see, your template file expects an input parameter called mapping, so you need change your main code to something like this:

    def f = new File('output.template')
    def engine = new groovy.text.GStringTemplateEngine()

    def mapping = [
        [ name : "param1", value : "1"],
        [ name : "param2", value : "2"]
    ] // This mapping can consists of a multiple key value pairs.

    def Template = engine.createTemplate(f).make([mapping: mapping])

    println "${Template}"

Output:

#cat output.template
env:
  - name : param1
    value : 1
  - name : param2
    value : 2
Edumelzer
  • 1,066
  • 1
  • 11
  • 22
  • It's ok and expected that a file ends with a new blank line, see [this link](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline) for example. But, your result will just have blank lines, if your template file has it too. – Edumelzer Mar 23 '18 at 13:09
  • @Here_2_learn Oh, and you can use `trim` on your result to remove spaces and blank lines. Like: `println "${Template}".trim()` – Edumelzer Mar 23 '18 at 14:16
  • posted a continuation of this question, https://stackoverflow.com/questions/49514779/groovy-multiple-loops-in-template-engine-using-gstringtemplateengine, can you check and help me. – Here_2_learn Mar 27 '18 at 13:53