开发者

Conditionally include attribute in XML literal

I have the following XML literal:

<input type='radio'
       name={funcName}
       value='true' />

I'd like to include checked='checked' if cond is true.

I've tried this,

<input type='radio'
       name={funcName}
       value='true'
       { if (cond) "checked='checked'" else "" } />

but it doesn't work.

(I'd really like to avoid repeating the whole tag开发者_JAVA技巧.)


Option also works, which reduces unnecessary use of null:

scala> val checked:Option[xml.Text] = None
checked: Option[scala.xml.Text] = None

scala> val xml = <input checked={checked} />
xml: scala.xml.Elem = <input ></input>


If you want to add the attribute only when checked, you can add it after using Scala XML API:

import scala.xml._

val snippet = {

  val x = <input type='radio'
                 name={funcName}
                 value='true' />

  if( cond ) {
    x % new UnprefixedAttribute("checked","checked",Null)
  } else x

}


Believe it or not, you can do it like this:

<input type='radio'
       name={funcName}
       value='true'
       checked={ if (cond) "checked" else null } />

This is one of the dark parts of Scala where null actually gets used.

Just to make clear, it does exactly what you want: if cond is false, then input will have no checked attribute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜