Search code examples
xmlscalalift

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


Solution

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