簡體   English   中英

如何同時使用有序參數和嵌套子字符串進行 Groovy 字符串插值?

[英]How to do Groovy string interpolation with ordered parameters & nested substrings at the same time?

我正在為 Jenkins 管道使用 Groovy,我想創建電子郵件模板字符串。 問題是我想將一個字符串嵌套在另一個字符串中,同時還具有有序參數。 我想要這樣的東西:

# 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.
                """

我試過:

  1. 帶有有序參數的sprintf (即 %1$s)(上面的例子)
    這幾乎是完美的,但是使用像 %1$s 這樣的有序參數對 GStrings ("") 不起作用,因為它們似乎會引發 MissingPropertyException。

  2. 簡單模板引擎
    該解決方案允許我指定我希望使用綁定的參數順序,但我認為我不能在這里使用嵌套字符串。 這是因為如果我使用 GString 而不是常規 String 以便我可以嵌套 shortEmail 變量,那么在初始化字符串時將為存儲在 ${} 中的其他變量引發 MissingPropertyException。

def longEmail = """|${shortEmail}
                   |
                   |# These bindings below would raise an Error
                   |Build Results: ${BUILD_RESULTS}
                   |Test Results: ${TEST_RESULTS} etc.
                """

我們可以使用轉義字符,即:

沖刺

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM