2

我想将一些辅助函数放在另一个文件中,因为它们会被过度重用。我拿了 Computer-Databse 样本的列表文件:

https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html

我在 app/views 包下创建了一个名为“listing.scala.html”的新文件,并将@link 函数从原始文件移到其中。这个新文件如下所示:

@(currentSortBy: String, currentOrder: String, currentFilter: String)

@****************************************
* Helper generating navigation links    *
****************************************@
@link(newPage:Int, newSortBy:String) = @{

    var sortBy = currentSortBy
    var order = currentOrder

    if(newSortBy != null) {
        sortBy = newSortBy
        if(currentSortBy == newSortBy) {
            if(currentOrder == "asc") {
                order = "desc"
            } else {
                order = "asc"
            }
        } else {
            order = "asc"
        }
    }

    // Generate the link
    routes.Application.listPerfil(newPage, sortBy, order, currentFilter)

}

所以,在我的原始文件中,我用这个替换了@link 调用:

<a href="@listing(currentSortBy, currentOrder, currentFilter).link(0, key)">@title</a>

问题是,当我尝试编译时出现此错误:

value link is not a member of play.api.templates.Html

但根据文档(http://www.playframework.org/documentation/2.0.4/ScalaTemplateUseCases),它似乎没问题。

有什么猜测吗?

4

1 回答 1

1

Play's templates aren't the best place for placing advanced conditions, most probably you'll get better flexibility by processing it in some controller (or other method) which will return you only required link

ie.:

 <a href="@controllers.Application.link(currentSortBy, currentOrder, currentFilter, 0, key)">@title</a>

In your case proposed link(...) function of Application controller can also return a reverse-route.

Keep in mind that including other templates is best option for repeating blocks of HTML but sometimes it's hard to get specified string (mainly because of not trimmed spaces). As you can see there is also problem with calling nested functions. Most probably you can generate whole A tag in the listing.scala.html however using it isn't comfortable enough (IMHO).

于 2012-11-05T21:28:34.803 回答