使用 Scala 和 StringTemplate,如何循环遍历 Map
我在 Google AppEngine 中使用 Scala、StringTemplate 很好地设置了我的环境。我在循环遍历地图并将其显示在模板中时遇到问题。当我将一个简单的字符串列表分配给模板时,它可以使用:
在 Scala Servlet 中:
var photos = List[String]()
//... get photo url and title ...
photos = photo_url :: photos
template.setAttribute("photos", photos: _*)
在模板中:
$photos: { photo|
<div><img src="$photo$_s.jpg"></div>
}$
上面的工作原理。但是,任何使用 url 和标题创建地图并分配给模板的尝试都会出现错误。这是我的尝试,但不起作用:
在 Scala Servlet 中:
var photos = List[Map[String,String]]()
//... get photo url and title ...
photos = Map("url" -> url, "title" -> title) :: photos
template.setAttribute("photos", photos: _*)
在模板中:
$photos: { photo|
<div><img src="$photo.url$_s.jpg" title="$photo.title$"></div>
}$
这给了我以下错误
Class scala.collection.immutable.Map$Map2 has no such attribute: title in template context
想法/想法?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Rex 的建议,我能够使用带有
@BeanProperty
字段注释的案例类来使其工作:这对我有用(使用 scalasti StringTemplate 库,您可能也已经这样做了)。
Following up on Rex's suggestion, I was able to make it work using a case class with a
@BeanProperty
annotation for the fields:This worked for me (using the scalasti library for StringTemplate, as you probably also already did).
有一个简单的替代方案,无需使用额外的包和注释。注册一个 scala 对象适配器,它知道如何从 scala 对象和 scala 集合中检索属性值。
现在,它包含在 StringTemplate 常见问题解答中:
http://www.antlr.org/wiki/display /ST4/改变+属性+查找+for+Scala
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