我想存储一个用户可配置的 GString ,该 GString 将绑定(bind)到一个域类,但我在找到一个很好的解决方案时遇到了问题。
示例( 概念/伪/非工作 )
class Person{
...
String displayFooAs; //<-- contains a java.lang.String like '${name} - ${address}'
}
class Foo{
String name;
String address;
String city;
public String getDisplayAs(def person){
return doStuff(this, person.displayFooAs); //<-- Looking for something simple.
}
}
更新:
经过审查,我决定这种灵 active 将构成 安全风险 .它将允许用户基本上将 sql 注入(inject)脚本写入“dispalyFooAs”。回到绘图板。
最佳答案
你的意思是像:
public String getDisplayAs(def person){
doStuff( this, person?.displayFooAs ?: "$name - $address" )
}
这在 Groovy 中有效,但我从未在 Grails 中将 SimpleTemplateEngine 嵌入到类似的东西中,因此需要进行大量测试以确保它按预期工作并且不会占用内存。
import groovy.text.SimpleTemplateEngine
class Person {
String displayAs = 'Person $name'
}
class Foo {
String name = 'tim'
String address = 'yates'
String getDisplayAs( Person person ) {
new SimpleTemplateEngine()
.createTemplate( person?.displayAs ?: '$name - $address' )
.make( this.properties )
.toString()
}
}
def foo = new Foo()
assert foo.getDisplayAs( null ) == 'tim - yates'
assert foo.getDisplayAs( new Person() ) == 'Person tim'
关于grails - 使用域类绑定(bind)在运行时评估 GString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123354/