Alvaro Cavalcanti
Alvaro Cavalcanti

Reputation: 3078

PlayFramework 2.0 - Not able to call functions from other templates

I want to place some helper functions in another file, since they will be overly reused. I took the Computer-Databse sample's listing file:

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

I created a new file, called "listing.scala.html" under the app/views package, and moved the @link function from the original file to it. This new file looks like this:

@(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)

}

So, on my original file, I replaced the @link call, with this one:

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

And the problem is, when I try to compile I get this error:

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

But according to the documentation (http://www.playframework.org/documentation/2.0.4/ScalaTemplateUseCases) it seems to be ok.

Any guess?

Upvotes: 2

Views: 943

Answers (1)

biesior
biesior

Reputation: 55798

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

Upvotes: 1

Related Questions