looping a template using groovy GStringTemplateEngine()

♀尐吖头ヾ 提交于 2019-12-25 00:22:17

问题


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:

回答1:


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


来源:https://stackoverflow.com/questions/49444475/looping-a-template-using-groovy-gstringtemplateengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!