gpt4 book ai didi

grails - 在 grails 中的字符串内插入变量

转载 作者:行者123 更新时间:2023-12-02 05:42:07 24 4
gpt4 key购买 nike

假设我有一个字符串以以下格式保存到数据库的域属性中

 "This variable needs to be interpolated: ${variable}."

从 Controller 中,我传递此变量的值,例如,“FooBar”。然后在 GSP 中,如果我执行某项操作,则页面。喜欢

<%
def testVar = ${MyDomainObj?.get(1)?.myProperty}
%>
variable is: ${variable}
variable is: ${testVar}

我得到的输出如下:

variable is: FooBar
variable is: "This variable needs to be interpolated: ${variable}."

查看直接从数据库返回的 ${variable} 没有被插入。需要做什么才能获得保存在数据库实例中的表达式 ${variable} 的正确插值形式。

最佳答案

尝试Groovy Templates .

您可以按照现在的方式将字符串保留在域中。要将变量绑定(bind)到字符串,您需要一个 groovy.text.SimpleTemplateEngine 实例,并对其调用 createTemplateEnginemake

import groovy.text.SimpleTemplateEngine
// ...
def engine = new SimpleTemplateEngine()
def binding = ["variable": variable]
def testVar = engine.createTemplate(MyDomainObj?.get(1)?.myProperty).make(binding)

您的输出将符合预期:

variable is: FooBar
variable is: "This variable needs to be interpolated: FooBar."

关于grails - 在 grails 中的字符串内插入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14828342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com