简体   繁体   中英

Grails - Set “disabled” attribute name and value in GSP

I´m trying to do this without success:

<g:textField title="${title}" ${disabled} />

I want to apply a disabled attribute, ONLY if the ${disabled} variable is TRUE. I don't want to use conditionals, because in other views I got a lot of code and using IF statements, will be a chaos.

The other thing is applying the attribute like this:

<g:textField title="${title}" disabled="${disabled}" />

But when I put the disabled attribute, no mather the content of the variable, It just always disables the field.

如果你不喜欢gotomanners的解决方案(这对我来说似乎完全有效)

<g:textField title="${title}" ${(disabled)?"disabled":""} />

your ${disabled} variable should be returning "disabled" not TRUE for that to work.

EDIT

I tried this out and saw the problem with it always being disabled no matter the value. Apparently the mere presence of the disabled keyword disables the field and the value assigned to that keyword is only a dummy value.

Anyway, Here's a fix.

  • Create a Taglib class(if you don't have one already)
  • define your own textfield tag as such...

     def myTextField = { attrs, body -> def title = attrs.remove("title") def isDisabled = attrs.remove("disabled") if ("true".equals(isDisabled)) { out << """<input title="${title}" disabled="${isDisabled}" """ attrs.each { k,v -> out << k << "=\\"" << v << "\\" " } out << "/>" } else { out << """<input title="${title}" """ attrs.each { k,v -> out << k << "=\\"" << v << "\\" " } out << "/>" } } 
  • in your gsp, call your textfield tag like so

     <g:myTextField title="${title}" disabled="${disabled}" /> 
  • adding extra attributes like so is also valid

     <g:myTextField class="title" name="theName" value="theValue" title="${title}" disabled="${disabled}" /> 
  • make sure your ${disabled} variable returns "true" or "false" as strings this time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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