Groovy 模板 - 非标准参数,带减号

Groovy Templates - Non Standard Parameters, with minus signs

我正在尝试渲染一个地图,其中的键包含减号(例如 first-name)。这是我尝试呈现的示例模板:

String text = "Dear \"$first-name $lastname\",\nSo nice to meet you";

当我使用 Groovy 模板引擎(可以是 SimpleTemplateEngineMarkupTemplateEngine)渲染它时,它会抱怨并抛出异常。当我从变量名中删除“-”时,它工作正常。

有没有办法在 Groovy 模板文本中转义这些变量?

顺便说一句 - 我这样做的原因是从第 3 方 API.

渲染一个 JSON blob

至少有一种方法可以做到。由于不能在变量名中使用 - 字符的相同原因,它在您的情况下不起作用。当您定义如下表达式时:

${first-name}

Groovy 将其视为:

${first.minus(name)}

这就是它抛出异常的原因:

Caught: groovy.lang.MissingPropertyException: No such property: first for class: SimpleTemplateScript1
groovy.lang.MissingPropertyException: No such property: first for class: SimpleTemplateScript1
    at SimpleTemplateScript1.run(SimpleTemplateScript1.groovy:1)

您可以在绑定中保留 first-name 之类的键,但您必须将它们放在映射中,以便您可以使用 Map.get(key) 函数访问 first-name 值。考虑以下示例:

import groovy.text.SimpleTemplateEngine

def engine = new SimpleTemplateEngine()
def bindings = [
        'first-name': 'Test',
        'lastname': 'qwe'
]

String text = 'Dear "${map["first-name"]} ${map["lastname"]}",\nSo nice to meet you'

println engine.createTemplate(text).make([map: bindings])

在此示例中,我将绑定放入具有键 map 的映射中。当我这样做时,我可以作为 map['first-name']map['lastname'] 访问我的绑定。 运行 这个例子产生了预期的输出:

Dear "Test qwe",
So nice to meet you

希望对您有所帮助。