避免在Groovy模板中使用新的折线

Rob*_*ert 7 groovy templates template-engine gstring

我有YAML file我的配置名称applications.yaml,该数据将被绑定我:

applications:
- name: service1
  port: 8080
  path: /servier1
- name: service2
  port: 8081
  path: /service2

Run Code Online (Sandbox Code Playgroud)

然后,我有一个模板文件applications.config

<% applications.each { application ->  %>
ApplicationName: <%= application.name %>
<% } $ %>
Run Code Online (Sandbox Code Playgroud)

然后放在一起:

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml

Yaml parser = new Yaml()
Map data = parser.load(("applications.yaml" as File).text)

String template_content = new File('applications.config').text
def binding = [applications: data.applications]

def template = new groovy.text.GStringTemplateEngine().createTemplate(template_content).make(binding)
println template.toString()
Run Code Online (Sandbox Code Playgroud)

现在的问题是:该过程的输出是:


ApplicationName: service1

ApplicationName: service2

Run Code Online (Sandbox Code Playgroud)

但是我想要这个:

ApplicationName: service1
ApplicationName: service2
Run Code Online (Sandbox Code Playgroud)

我不知道为什么那里有多余的空间。我想删除这些内容,但看不到如何,何时或什么放置这些新的或折线

谢谢。

Bha*_*mar 5

我观察到(从答案、评论和一些实践)是:new Lines我们在文件内创建的所有内容都applications.config被视为new line在输出中。正如达吉特所说,这是默认的事情。

所以在这里我只想展示可能的config文件格式,可以conditional logic根据您的要求应用一些文件格式,并且对我来说看起来不错。前任 :if()

应用程序配置:

<% applications.each { application ->
 if (application.valid) {%>\
Type :<%=application.valid%>
ApplicationName:<%=application.name%>
Path:<%=application.path%>
Port:<%=application.port%>
<%} else{%>\
--------------------
Found invalid Application : <%= application.name %>
--------------------\
<%}}%>
Run Code Online (Sandbox Code Playgroud)

应用程序.yaml

applications:
- name: service1
  port: 8080
  path: /servier1
  valid: true
- name: service2
  port: 8081
  path: /service2
  valid: false
Run Code Online (Sandbox Code Playgroud)

代码.groovy

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml

Yaml parser = new Yaml()
Map data = parser.load(("applications.yaml" as File).text)

String template_content = new File('applications.config').text

def binding = [applications: data.applications]
def template = new groovy.text.GStringTemplateEngine().createTemplate(template_content).make(binding)
println template.toString()
Run Code Online (Sandbox Code Playgroud)

输出 :

Type :true
ApplicationName:service1
Path:/servier1
Port:8080
--------------------
Found invalid Application : service2
--------------------
Run Code Online (Sandbox Code Playgroud)