[英]How to do Groovy string interpolation with ordered parameters & nested substrings at the same time?
I'm using Groovy for Jenkins pipelines and I want to create email template strings.我正在为 Jenkins 管道使用 Groovy,我想创建电子邮件模板字符串。 The issue, is I want to have one string nested in another one, while also having ordered parameters.问题是我想将一个字符串嵌套在另一个字符串中,同时还具有有序参数。 I want something like this:我想要这样的东西:
# To use if job aborts/ends early
def shortEmail = """|Title: %1$s
|Link: %2$s etc.
"""
# To use if the job is able to finish to completion
def longEmail = """|${shortEmail}
|
|Build Results: %3$s
|Test Results: %4$s etc.
"""
I tried:我试过:
sprintf with ordered params (ie. %1$s) (example above)带有有序参数的sprintf (即 %1$s)(上面的例子)
This would almost be perfect but using ordered parameters like %1$s don't work on GStrings ("") since they seem to raise a MissingPropertyException.这几乎是完美的,但是使用像 %1$s 这样的有序参数对 GStrings ("") 不起作用,因为它们似乎会引发 MissingPropertyException。
SimpleTemplateEngine简单模板引擎
This solution allowed me to specify the parameter ordering I would like with the use of bindings, but I don't think I can use nested strings here.该解决方案允许我指定我希望使用绑定的参数顺序,但我认为我不能在这里使用嵌套字符串。 This is because if I use a GString rather than a regular String so that I can nest the shortEmail variable, then a MissingPropertyException will be raised for the other variables that are stored in ${} when the string is initialized.这是因为如果我使用 GString 而不是常规 String 以便我可以嵌套 shortEmail 变量,那么在初始化字符串时将为存储在 ${} 中的其他变量引发 MissingPropertyException。
def longEmail = """|${shortEmail}
|
|# These bindings below would raise an Error
|Build Results: ${BUILD_RESULTS}
|Test Results: ${TEST_RESULTS} etc.
"""
We can use the escape character, ie:我们可以使用转义字符,即:
sprintf :冲刺:
def shortEmail = """|Title: %1\$s
|Link: %2\$s etc.
"""
def longEmail = """|${shortEmail}
|
|Build Results: %3$s
|Test Results: %4$s etc.
|Title Again: %1\$s
"""
printf(sprintf(longEmail, [
'My Title', 'My Link','Some Build', 'Some Tests'
]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.