Conditionally include attribute in XML literal
Asked Answered
T

3

25

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

Thyme answered 28/7, 2011 at 9:35 Comment(1)
Possible duplicate of How do I add an XML attribute, or not, depending on an Option?Napoleonnapoleonic
N
30

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>
Noelyn answered 29/7, 2011 at 0:19 Comment(1)
One can also use opt.orNull to skip converting to xml.Text.Sophey
M
9

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.

Margo answered 28/7, 2011 at 22:28 Comment(2)
Avoid using null in attribute values. It causes a fair number of problems in other parts of the 2.8 XML libraries.Unquote
@DavidPollak Are you sure? When checking in the console, it seems the attribute is not created at all in this case.Napoleonnapoleonic
O
8

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

}
Osi answered 28/7, 2011 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.