简体   繁体   English

在GSP中打印时,在变量中评估Groovy / Grails代码

[英]Evaluate Groovy/Grails Code in variable when printing it in GSP

I have a GSP page containing different input elements related to a specific context. 我有一个GSP页面,其中包含与特定上下文相关的不同输入元素。 For example I can display a textfield for usecase A, but not for usecase B (short version, it's very complex actually) 例如,我可以显示用例A的文本字段,但不能显示用例B的文本字段(简短版本,实际上非常复杂)

For this I have a domain object, which is normally populated with plain static HTML. 为此,我有一个域对象,通常用普通的静态HTML填充。 But now I need to add dynamic data, like this: 但是现在我需要添加动态数据,如下所示:

def field = new InputField()
field.code = '<input type="text" name="foo" value="${currentUser.name}" />'
// or: field.code = '<option value="1"><g:message code="someCode"/></option>'

This code is stored in database. 此代码存储在数据库中。 It will be rendered later on in GSP: 稍后将在GSP中呈现:

<g:each in="${InputField.findAllBySomeCondition(...)}">
    ${it.code}
</g:each> 

This will print the input element, but instead of evaluating the dynamic code ( ${currentUser.name} ) it is just printed as plain text. 这将打印输入元素,但不是评估动态代码( ${currentUser.name} ),而是将其打印为纯文本。

Unfortunately I can't change the whole process, there are over 3000 different input elements stored already, but none of them are dynamic. 不幸的是,我无法更改整个过程,已经存储了3000多个不同的输入元素,但是它们都不是动态的。

Is there a way to tell Grails to evaluate code within the variable before printing it? 有没有办法告诉Grails在打印变量之前先对变量中的代码求值?

edit: I'm using Grails 2.2.4 编辑:我正在使用Grails 2.2.4

That's because you're using ' for the string, not ". When using ' the result is a String, not a GString with variable evaluation. 这是因为您使用的是字符串',而不是'。使用'时,结果是字符串,而不是带有变量求值的GString。

Try changing to: 尝试更改为:

field.code = "<input type=\"text\" name=\"foo\" value=\"${currentUser.name}\" />"

or use the triple version """ to avoid escaping: 或使用三元版本“””以避免转义:

field.code = """<input type="text" name="foo" value="${currentUser.name}" />"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM