|
| 1 | +/* |
| 2 | + * Copyright (C) Lightbend Inc. <https://www.lightbend.com> |
| 3 | + */ |
| 4 | +package play.twirl.api |
| 5 | + |
| 6 | +import java.util.Optional |
| 7 | +import scala.collection.immutable |
| 8 | +import scala.jdk.CollectionConverters._ |
| 9 | +import scala.reflect.ClassTag |
| 10 | + |
| 11 | +case class BaseScalaTemplate[T <: Appendable[T], F <: Format[T]](format: F) { |
| 12 | + // The overloaded methods are here for speed. The compiled templates |
| 13 | + // can take advantage of them for a 12% performance boost |
| 14 | + def _display_(x: AnyVal): T = format.escape(x.toString) |
| 15 | + def _display_(x: String): T = if (x eq null) format.empty else format.escape(x) |
| 16 | + def _display_(x: Unit): T = format.empty |
| 17 | + def _display_(x: scala.xml.NodeSeq): T = if (x eq null) format.empty else format.raw(x.toString()) |
| 18 | + def _display_(x: T): T = if (x eq null) format.empty else x |
| 19 | + |
| 20 | + def _display_(o: Any)(implicit m: ClassTag[T]): T = { |
| 21 | + o match { |
| 22 | + case escaped if escaped != null && escaped.getClass == m.runtimeClass => escaped.asInstanceOf[T] |
| 23 | + case () => format.empty |
| 24 | + case None => format.empty |
| 25 | + case Some(v) => _display_(v) |
| 26 | + case key: Optional[_] => |
| 27 | + (if (key.isPresent) Some(key.get) else None) match { |
| 28 | + case None => format.empty |
| 29 | + case Some(v) => _display_(v) |
| 30 | + case null => format.empty |
| 31 | + } |
| 32 | + case xml: scala.xml.NodeSeq => format.raw(xml.toString()) |
| 33 | + case escapeds: immutable.Seq[_] => format.fill(escapeds.map(_display_)) |
| 34 | + case escapeds: TraversableOnce[_] => format.fill(escapeds.iterator.map(_display_).toList) |
| 35 | + case escapeds: Array[_] => format.fill(escapeds.view.map(_display_).toList) |
| 36 | + case escapeds: java.util.List[_] => |
| 37 | + format.fill(escapeds.asScala.map(_display_).toList) |
| 38 | + case string: String => format.escape(string) |
| 39 | + case v if v != null => format.escape(v.toString) |
| 40 | + case null => format.empty |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments