Last active
August 29, 2015 14:02
-
-
Save tstone/db350000ba9230bdfa38 to your computer and use it in GitHub Desktop.
Angular Style Filters in Scala/Twirl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- 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> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're wondering why
|||
instead of just|
, it's because Twirl has|
already setup to be a boolean comparison operator.