Search code examples
scalaplayframeworkplayframework-2.3twirl

Twirl: tags/views with optional content


I want to create a tag with optional content... Let's say that I have a tag:

app/views/tags/part.scala.html:

@(param: String)(content: Html = null)

@if(content == null) {
    @param: Your tag has no content...
} else {
    @param: @content
}

And I'd like to use it in my views as:

@tags.part("foo"){ <b>Good!</b} }

or

@tags.part("bar")

Unfortunately second call gives me the compilation error:

missing arguments for method apply in object part;

follow this method with `_' if you want to treat it as a partially applied function

How can I pass it without using @tags.part("bar"){ } or @tags.part("bar"){_} (and check in tag if body != "_")?


Solution

  • Your call:

    @tags.part("bar")
    

    is curry call - it returns function apply - not a object.

    The solution for your code is call apply function:

    @tags.part("bar")()
    

    If you want to call:

    @tags.part("bar")
    

    you should to define

    @(param: String)(implicit content: Html) 
    

    and define implicit Html in context, or define as

    @(param: String,content: Html = null)
    
    • but then you have to call:

    @tags.part("foo")(Html("<b>Good!</b>")) - what is error prone.

    The work around for last solution is to create method and call it:

    @good = {<b>Good!</b>}
    
    @tags.part("foo")(good)