【发布时间】:2017-01-09 09:56:09
【问题描述】:
假设我有一个名为 Template 的域类,它看起来有点像这样:
class Template{
String subject
...
}
我保存了这个类的一个实例:
Template t=new Template(subject:'Hello ${name}').save()
现在,我在一个方法中获取这个实例,如下所示:
def render(Long id){
String name='foo'
Template t= Template.get(id)
println t.subject
}
我希望将“println t.subject”打印为“Hello foo”。我得到的是“你好 ${name}”。 我希望 t.subject 动态替换变量名称的值 - "foo" 代替 ${name}。
这可以在 groovy 中实现吗? 我找不到任何有关如何执行此操作或为什么无法执行此操作的文档。
更新:
我在我的 GroovyConsole 上试过这个。
class Entity{
String name
}
class Template{
String name
String subject
}
String renderTemplate(Template template, Entity entity){
return template.subject
}
Entity e = new Entity(name:'product')
Template template=new Template(name:'emailTemplate',subject:'Product ${e.name}')
renderTemplate(template,e)
我得到的输出是:
结果:产品产品
【问题讨论】:
-
可能是因为您应该使用 messages.properties 和 gsps 来呈现模板,而不是使用 db 作为模板 :)
-
感谢您的回复。这是我知道的解决方案。但我特别想将上述作为一个用例来实现。
-
你确定你有
new Template(subject:"Hello ${name}")而不是new Template(subject:'Hello ${name}')吗?双引号很重要。您描述的行为没有意义,几乎是不可能的。 -
杰夫。抱歉,我错过了这条评论。是的。这是一个单引号。对于由于单引号引起的误导,我深表歉意。