Idiomatic optional classes and attributes

55 views
Skip to first unread message

Byron Weber Becker

unread,
May 6, 2014, 11:51:03 PM5/6/14
to scal...@googlegroups.com

I sometimes want to do something like the following:

val myClassAttr = `class` := if (someCondition) "doSomethingSpecial" else ""

...
p(myClassAttr)("The contents of my paragraph")
...

This works, but it generates <p class="">The contents of my paragraph</p>, which doesn't feel very elegant to me when someCondition is false.

I think my question boils down to whether there is a way to generate a null attribute that expands to nothing when the html is generate.

Thanks!
Byron

Haoyi Li

unread,
May 7, 2014, 12:17:34 AM5/7/14
to Byron Weber Becker, scal...@googlegroups.com
So far I've adopted this pattern:

scala> val someCondition = false
someCondition: Boolean = false

scala> val myClassAttr = if (someCondition) Some(`class` := "doSomethingSpecial") else None
myClassAttr: Option[scalatags.AttrPair] = None

scala> p(myClassAttr)("The contents of my paragraph")
res2: scalatags.HtmlTag = <p>The contents of my paragraph</p>

It would be better if there was a Boolean.toOption method, but that's somewhat beyond the scope of Scalatags. e.g. with scalaz you could write

val myClassAttr = someCondition.option(`class` := "doSomethingSpecial") 

Which looks considerably better.


--
You received this message because you are subscribed to the Google Groups "Scalatags" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatags+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Byron Weber Becker

unread,
May 7, 2014, 7:46:53 AM5/7/14
to Haoyi Li, scal...@googlegroups.com
Nice!  Thank you.
Reply all
Reply to author
Forward
0 new messages