How to insert html code in a scalatags atribute?

235 Views Asked by At

I have a button that gets used as a popover with Twitter's bootstrap.

button(data.content := h1("an example of html").render, data.toggle="popover")("click here")

I want to have some html code in the content of the popover, so I need to pass html to the data.toggle atribute, however this prints the html code out plain, because of scalatags preventing XSS. How can I prevent this / how else can I get this effect?

1

There are 1 best solutions below

0
danielnixon On

This is gnarly but it'll do what you want. I'm not sure there's a nicer way.

import scalatags.Text.{Attr, TypedTag}
import scalatags.Text.all._
import scalatags.text.Builder

// Warning: this extends a "more-or-less internal trait" so may stop working after a ScalaTags update.
final case class RawValueSource(v: String) extends Builder.ValueSource {
  override def appendAttrValue(strb: StringBuilder): Unit = strb.append(v)
}

// We need an AttrValue for tags. This one just renders the tag *without* escaping the result.
class TagAttrValue extends AttrValue[TypedTag[String]] {
  override def apply(t: Builder, a: Attr, v: TypedTag[String]): Unit = {
    t.setAttr(a.name, RawValueSource(v.render))
  }
}

// We need this implicit in scope so that we can use tags on the rhs of the := operator.
implicit val tagAttr = new TagAttrValue()

button(data.content := h1("an example of html"), data.toggle := "popover")("click here")