I have my environment setup nicely using Scala, StringTemplate within the Google AppEngine. I am having trouble looping through a Map and getting it to display in the template. When I assign a simple List of just Strings to the template it works using:
In Scala Servlet:
var photos = List[String]()
//... get photo url and tit开发者_开发百科le ...
photos = photo_url :: photos
template.setAttribute("photos", photos: _*)
In Template:
$photos: { photo|
<div><img src="$photo$_s.jpg"></div>
}$
The above works. However, any attempt of creating a Map using url and title and assigning to the template gives me an error. Here is my attempt, which does not work:
In Scala Servlet:
var photos = List[Map[String,String]]()
//... get photo url and title ...
photos = Map("url" -> url, "title" -> title) :: photos
template.setAttribute("photos", photos: _*)
In Template:
$photos: { photo|
<div><img src="$photo.url$_s.jpg" title="$photo.title$"></div>
}$
This gives me the following error
Class scala.collection.immutable.Map$Map2 has no such attribute: title in template context
Thoughts / Ideas ?
Following up on Rex's suggestion, I was able to make it work using a case class with a @BeanProperty
annotation for the fields:
case class MyPhoto(@BeanProperty val url: String, @BeanProperty val title: String)
def generateMyPhotos() : String = {
val tp = new StringTemplate("$photos: { photo|<div><img src=\"$photo.url$_s.jpg\" title=\"$photo.title$\"></div>}$")
val photos = List(MyPhoto("http://myphoto.com", "my photo"))
tp.setAttribute("photos", photos: _*)
tp.toString
}
This worked for me (using the scalasti library for StringTemplate, as you probably also already did).
There's a simple alternative, without using additional packages and annotations. Register a scala object adaptor that knows how to retrieve property values from scala objects and scala collections.
This is now included in the StringTemplate FAQ at: http://www.antlr.org/wiki/display/ST4/Altering+property+lookup+for+Scala
精彩评论