本文介绍了定义和引用Play模板签名中绑定的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多排序的地图,按时间排序,并有某种类型的值。为了说明,考虑我有3张地图(用Java):

  SortedMap< OffsetDateTime,Foo> FOO; 
SortedMap< OffsetDateTime,Boo>酒吧;
SortedMap< OffsetDateTime,Baz>巴兹;

我希望编写一个接受地图和渲染器函数的通用Play模板,

在一个模板中,我可以使用以下签名定义一个 local 函数:

  @renderTrace [T   

然而,我想在多个模板中使用这个函数,所以我没有想要在本地定义它。相反,我希望将其定义为自己的模板(在 RenderTrace.scala.html 中)。



不幸的是,我似乎无法指定类型结构 [T<:Any] 在模板签名中。



如何定义一个可重用的一般类型函数?

解决方案

为了充实@Ashalynd的建议,模板编译器看起来不够聪明,无法处理类型参数。有时你可以使用下划线作为类型参数(只有当你不关心类型是什么时),但这不是这种情况之一。



A Play(现在称为twirl)模板基本上只是一个产生类型结果的函数。play.twirl.api.Html (或者 play.api.templates .Html 用于Play 2.2)。模板编译器需要解决,所以定义一个包含你的函数的帮助程序包:

 包viewhelpers 

导入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 = ...

}
pre>

执行 renderTrace 可能看起来不像在视图模板中那么好,但至少它

然后在视图中:

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

@ {ViewExtension.renderTrace(...)}


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?

解决方案

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

这篇关于定义和引用Play模板签名中绑定的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:23