Groovy模板含连字符的非标准参数渲染问题
解决Groovy模板中带连字符的变量渲染问题
可行的解决方案
不管你用的是SimpleTemplateEngine还是MarkupTemplateEngine,核心思路都是绕过直接使用带连字符的变量名,转而通过binding对象的索引访问来获取对应的值。
举个SimpleTemplateEngine的实际示例:
import groovy.text.SimpleTemplateEngine // 模板里通过binding['键名']的方式访问带连字符的变量 def templateText = 'Dear "${binding[\'first-name\']} ${lastname}",\nSo nice to meet you' def engine = new SimpleTemplateEngine() def template = engine.createTemplate(templateText) // 传入包含带连字符键的Map def result = template.make([ 'first-name': 'Jane', lastname: 'Smith' ]) println result.toString()
如果是MarkupTemplateEngine,写法几乎一致:
import groovy.text.markup.MarkupTemplateEngine import groovy.text.markup.TemplateConfiguration def config = new TemplateConfiguration() def engine = new MarkupTemplateEngine(config) def template = engine.createTemplate('Dear "${binding[\'first-name\']} ${lastname}",\nSo nice to meet you') def output = template.make([ 'first-name': 'Jane', lastname: 'Smith' ]).toString() println output
问题出现的原因
之所以直接写$first-name会报错,本质是Groovy模板的解析逻辑导致的:
- Groovy模板会把
$后面的内容当成Groovy表达式来解析,而不是单纯的变量名。 - 在Groovy语法里,连字符
-是减法运算符,所以$first-name会被解析成「变量first减去变量name」的表达式。 - 当你的binding里没有
first和name这两个变量时,就会抛出MissingPropertyException之类的异常;就算有这两个变量,结果也完全不是你想要的。
而去掉连字符后,$firstname是一个合法的Groovy变量名,解析器能正确识别并从binding中取出对应的值,所以就能正常运行了。
内容的提问来源于stack exchange,提问作者Justin Lawler
相关产品推荐
相关产品推荐

