Skip to content

Instantly share code, notes, and snippets.

@tstone
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tstone/db350000ba9230bdfa38 to your computer and use it in GitHub Desktop.
Save tstone/db350000ba9230bdfa38 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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