如何使用SimpleTemplateEngine遍历模板中的列表

Pie*_*ult 1 groovy templates

我想知道是否可以遍历SimpleTemplateEngine groovy中的值列表。例如:

def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''\
    ???
'''
def template = engine.createTemplate(text).make(values)
println template.toString()
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到:

1
2
3
Run Code Online (Sandbox Code Playgroud)

通过更改变量text

lap*_*ots 9

def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''<% values.each { println it} %>'''
println engine.createTemplate(text).make([values: values])
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案按预期工作,上面在末尾打印了冗余数组 [1,2,3] (2认同)

dma*_*tro 5

你的意思是?

def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''
    ${values.each { println it} }
'''
println engine.createTemplate(text).make([values: values])
Run Code Online (Sandbox Code Playgroud)

  • 使用此代码时出现以下错误:`StreamingTemplateScript23.groovy: 1: unexpected char: 0xFFFF @ line 1, column 308.` (newline) `or(_i, _s, e);}}.asWritable()}` (3认同)

Abd*_*UMI 5

如果您想要一个没有很多引号并且没有大量命令式编程的优雅模板,您可以执行以下操作

def text = '''
<% for (item in values) { %>
<%= item %>    
<% } %>

'''
Run Code Online (Sandbox Code Playgroud)

规则很简单:

  • <%= ..%>如果有价值呈现就使用。
  • <% .. %>如果存在流程控制处理(if/else、for 循环...),则使用