views:

175

answers:

1

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 title ...

  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 ?

+3  A: 

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).

Arjan Blokzijl
Awesome, that worked! Thank you!! Yep, I am using scalasti wrapper for StringTemplate. The only thing I had to do was add an import for Bean Property import scala.reflect._
Marcus Kazmierczak