Defining and referencing a generic type bound in Play template signature

房东的猫 提交于 2019-12-23 18:45:58

问题


I have a number of sorted maps, keyed by a time and with a value of some type. For illustration, consider that I have 3 maps (in Java):

SortedMap<OffsetDateTime, Foo> foo;
SortedMap<OffsetDateTime, Boo> bar;
SortedMap<OffsetDateTime, Baz> baz;

I wish to write a generic Play template that accepts a map, and a renderer function, and outputs each pair.

Within a template, I can define a local function with the following signature:

@renderTrace[T <: Any](trace: ImmutableSortedMap[OffsetDateTime, Option[T]], renderer: (T) => Html) = {

However, I would like to use this function in multiple templates, so I do not want to define it locally. Rather, I had hoped to define it as its own template (in RenderTrace.scala.html).

Unfortunately, I don't seem be able able to specify the type construction [T <: Any] in the template signature.

How can I define a re-usable, generically typed function?


回答1:


To flesh out @Ashalynd's suggestion, the template compiler doesn't appear to be smart enough to handle type parameters. Sometimes you can use an underscore as the type parameter (only when you don't care what the type is), but this isn't one of those cases.

A Play (now called twirl) template is essentially just a function that produces result of type play.twirl.api.Html (or play.api.templates.Html for Play 2.2). The templates compiler needs to be worked around, so define a helper package containing your function:

package viewhelpers

import play.twirl.api.Html // play.api.templates.Html for 2.2

object ViewExtension {

    def renderTrace[T <: Any](trace: ImmutableSortedMap[OffsetDateTime, Option[T]], renderer: (T) => Html): Html = ...

}

The implementation of renderTrace might not look as nice as it would in the view template, but at least it can work now.

Then in a view:

@(someParams: ....)
@import viewhelpers.ViewExtension

@{ViewExtension.renderTrace(...)}


来源:https://stackoverflow.com/questions/24359359/defining-and-referencing-a-generic-type-bound-in-play-template-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!