Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally include attribute in XML literal

Tags:

xml

scala

lift

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

like image 389
aioobe Avatar asked Jul 28 '11 09:07

aioobe


3 Answers

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>
like image 155
Kristian Domagala Avatar answered Nov 11 '22 23:11

Kristian Domagala


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

}
like image 35
paradigmatic Avatar answered Nov 11 '22 21:11

paradigmatic


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.

like image 8
Daniel C. Sobral Avatar answered Nov 11 '22 22:11

Daniel C. Sobral