Conditionally include attribute in XML literal Conditionally include attribute in XML literal xml xml

Conditionally include attribute in XML literal


Option also works, which reduces unnecessary use of null:

scala> val checked:Option[xml.Text] = Nonechecked: Option[scala.xml.Text] = Nonescala> 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.