Here_2_learn
Here_2_learn

Reputation: 5451

looping a template using groovy GStringTemplateEngine()

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:

Upvotes: 1

Views: 2478

Answers (1)

Edumelzer
Edumelzer

Reputation: 1086

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

Upvotes: 2

Related Questions