如何有条件地创建 HTML 节点的绑定?

How do I create a Binding of HTML node conditionally?

我想有条件地创建 HTML 节点的绑定。

@dom def maybeEmpty: Binding[Node] = {
  if (math.random > 0.5) {
    <div>non-empty content</div>
  }
}

但是代码无法编译。

error: type mismatch;
 found   : Unit
 required: org.scalajs.dom.raw.Node

您需要一个内容为空的 else 块,通常是 HTML 评论:

@dom def maybeEmpty: Binding[Node] = {
  if (math.random > 0.5) {
    <div>non-empty content</div>
  } else {
    <!-- empty content -->
  }
}

因为 Binding.scala 11.1.x 你可以写:

@dom def maybeEmpty: Binding[Option[Node]] = {
  if (math.random > 0.5) {
    Some(<div>non-empty content</div>)
  } else {
    None
  }
}