Jan Krakora
Jan Krakora

Reputation: 2610

Including reusable blocks from a template into another template

I would like to use a reusable block from a template in my another templates. How can I do that? More specifically:

I have a template views/main.scala.html containing this tag

@logo_header = {
    <div id="logo-container">
       ...
    </div>
}

an I have another template views/errors/notFound.scala.html where I would like to include the logo_header tag from main template. I try @main.logo_header, or @main.logo_header() but the compile always says:

value logo_header is not a member of object views.html.main

I have looked in the official documentation where they describe including, but I can't understand why it not works.

Upvotes: 5

Views: 2161

Answers (1)

avik
avik

Reputation: 2708

You've done something slightly different to the usage mentioned in the documentation. In the documentation, the reusable tag is declared in its own file. What you're trying to do is declare a helper function in one view template and then try to call it from another template. As mentioned in this answer, a function is only visible to the view template in which it was declared.

What you need to do is move your logo header markup out into its own file:

views/_logo_header.scala.html

<div id="logo-container">
   ...
</div>

Then reference it as follows:

views/main.scala.html

<html>
    ...
    _logo_header
    ...
</html>

I've given the new file a name with a leading underscore as this is a common naming convention that marks the file out as containing a snippet of HTML rather than a full HTML document.

Finally, I've assumed that your logo header snippet doesn't need to take in any arguments. If it does, you can sprinkle in some Scala as mentioned in the documentation:

views/_logo_header.scala.html

@(arg1: String, arg2: String)
<div id="logo-container">
   ...
</div>

views/main.scala.html

<html>
    ...
    _logo_header("foo", "bar")
    ...
</html>

Upvotes: 5

Related Questions