Grails - 在GSP中设置“disabled”属性名称和值

5

我一直在尝试做这件事情,但没有成功:

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

如果${disabled}变量为TRUE,我希望应用一个disabled属性。但是我不想使用条件语句,因为在其他视图中有很多代码,使用IF语句会非常混乱。

另外一件事是像这样应用属性:

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

但是当我加上 disabled 属性时,无论变量的内容是什么,它都会禁用该字段。


请编辑您的问题陈述,明确表达您的意图。您对gotomanners的回答的评论似乎与您的问题相矛盾。 - Jim Norman
2个回答

8
如果您不喜欢gotomanners的解决方案(我认为它是完全有效的),请参考以下内容。
<g:textField title="${title}" ${(disabled)?"disabled":""} />

1
但它是有效的HTML - 这是我们大多数人现在创建的内容(如果您在许多年后看到此答案)。 - erichelgeson

7

你的${disabled}变量应该返回“disabled”,而不是TRUE,才能使其起作用。

编辑

我尝试了一下,发现它始终是禁用的,无论值是什么。显然,禁用关键字的存在会禁用该字段,分配给该关键字的值只是一个虚拟值。

无论如何,这里有一个修复方法。

  • 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.


感谢您的回复。我并不关心禁用变量及其内容。我只需要编写一个属性,例如: <g:textField title="${title}" ${disabled} /> 其中${disabled}包含一个字符串:'title="输入标题"'。 - David Morabito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接