Option[] and Mustache templates

186 views
Skip to first unread message

Wille Faler

unread,
Jan 14, 2011, 3:40:00 PM1/14/11
to sca...@googlegroups.com
Hi guys,
Yet another mustache question:
Is there any way of automatically unwrapping an option value in Mustache?

For instance, given:
case class Widget(name: Option[String)
viewModel = Map("widget" -> Widget(Some("someWidget"))

..and the template: 
        {{#widget}}
            Name: {{name}}
        {{/widget}}

..it will render "Name: Some(someWidget)"

..which really isn't very useful, as Option/Some/None are primarily Scala constructs, not for human reading in a result of a template..

/ Wille

James Strachan

unread,
Jan 16, 2011, 2:38:08 AM1/16/11
to sca...@googlegroups.com

Great catch! We'd supported handling None properly (like null) for the
longest time, but were not unwrapping the Some.

I've raised this issue
http://www.assembla.com/spaces/scalate/support/tickets/197

Its always surprised me a little that Option doesn't implement
Traversable, so I've also raised this issue so that when using an
Option[Person] value you can use it in a mustache section / inverted
section to iterate over a complex object wrapped in an Option
http://www.assembla.com/spaces/scalate/support/tickets/198

Both these issues are now resolved in master. See the test case for
more detail...
https://github.com/scalate/scalate/blob/master/scalate-core/src/test/scala/org/fusesource/scalate/mustache/OptionTest.scala#L26


Incidentally if you're ever wondering how Mustache navigates object
contexts and implements sections, its all in this Scope.scala file..
https://github.com/scalate/scalate/blob/master/scalate-core/src/main/scala/org/fusesource/scalate/mustache/Scope.scala

And here's the generic Scalate way we turn values into markup/output
handling null & None (and now Some) etc
https://github.com/scalate/scalate/blob/master/scalate-core/src/main/scala/org/fusesource/scalate/RenderContext.scala#L193

--
James
-------
FuseSource
Email: ja...@fusesource.com
Web: http://fusesource.com
Twitter: jstrachan
Blog: http://macstrac.blogspot.com/

Open Source Integration

Trevor Hartman

unread,
Jul 9, 2012, 8:22:24 PM7/9/12
to sca...@googlegroups.com
Looks like this doesn't work as expected when it's an Option[List[T]].

It treats it like a boolean and never iterates through the list.

    val foo = Some(List(1, 2, 3))

    {{#foo}}
      this is foo {{.}}
    {{/foo}}

Expected output:
    this is foo 1
      this is foo 2
      this is foo 3

Actual output:
    this is foo 123


Reply all
Reply to author
Forward
0 new messages