Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Style Filters in Scala/Twirl
// ---- Presenter Pattern ----
// presenters.scala
object presenters {
implicit class StringPresenter(s: String) {
def reverse = Html(s.reverse)
}
implicit DateTimePresenter(dt: DateTime){
def format(f: String) = DateTimeFormat.forPattern(f).print(dt)
}
}
// index.scala.html
@import presenters._
@main {
<h1>@message.reverse</h1>
<h3>@event.start.format("YYYY-MM-dd")</h3>
}
// -------------------------------------------------------
// ---- Filter Pattern ----
// filters.scala
object filters {
// --- Setup (once for all filters) ---
type HtmlFilter[A] = (A) => Html
implicit class Filtererer[A](a: A) {
def |||(filter: HtmlFilter[A]): Html = filter(a)
}
// --- Filter Examples ---
val reverse = new HtmlFilter[String] {
def apply(s: String) = Html(s.reverse)
}
def format(f: String) = new HtmlFilter[DDateTime] {
def apply(date: DateTime) = Html(DateTimeFormatter.forPattern(f).print(date))
}
}
// index.scala.html
@import filters._
@main {
<h1>@{ message ||| reverse }</h1>
<span>@{ event.start ||| format("YYYY-MM-dd") }</span>
}
@tstone

This comment has been minimized.

Owner

tstone commented Jun 18, 2014

If you're wondering why ||| instead of just |, it's because Twirl has | already setup to be a boolean comparison operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment