如何使用groovy模板处理布尔属性?

时间:2015-10-15 14:07:13

标签: spring-mvc groovy

给出以下groovy模板元素:

select(class: 'form-control input-sm',
       disabled: isDisabled)

如果isDisabled为true,我只是不想禁用select。问题是HTML认为禁用的存在足以禁用该元素。

2 个答案:

答案 0 :(得分:2)

有趣的问题,我没有比仅仅做这样的事情更好的想法:

isDisabled ? select(class: 'form-control input-sm', disabled:'disabled') : select(class: 'form-control input-sm')

[已更新] 或此:

def selectAttrs = [class: 'form-control input-sm']
if (isDisabled) selectAttrs += [disabled:'disabled']
select(selectAttrs)

完整的测试脚本:

import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration

model = [isDisabled:true]

def config = new TemplateConfiguration()
MarkupTemplateEngine engine = new MarkupTemplateEngine(config)
def template = engine.createTemplate '''
html {
body {
      isDisabled ? select(class: 'form-control input-sm', disabled:'disabled') : select(class: 'form-control input-sm')

      def selectAttrs = [class: 'form-control input-sm']
      if (isDisabled) selectAttrs += [disabled:'disabled']
      select(selectAttrs)
}
}
'''

StringWriter rendered = new StringWriter()
template.make(model).writeTo(rendered)

print rendered

答案 1 :(得分:0)

我不熟悉Groovy模板,但它是否可以与三元表达式一起使用?可能将表达式更改为:

select(class: 'form-control input-sm' ${isDisabled?", disabled":""})

如果disabled为真,则只包含isDisabled属性。