play-framework
Last year I’ve regularly worked with Play! Framework and it’s really awesome for development of modern web-applications. Since almost all my activity was focused on development of REST API I’ve used mainly Controllers and JSON stuff. But recently I needed to work with Twirl template engine. And this circumstance served for writing of current post.

So the problem was in a repeated HTML code. I needed to reduce a number of boilerplate code in already existed templates (e.g. footer, sidebar, menu e.t.c). The best way for solution of the problem is to use well known “include pattern”. All repeated code snippets need to be declared separately and then we can use them as a LEGO blocks to compose entire pages.

Let’s assume that we have main page: index.scala.html

<html>
<head>
<title>Main page</title>
</head>

<body>

<div>
Header
</div>

<div>
<h1>Main page</h1>
<p>A lot of text here which can be changed from page to page.</p>
</div>

<div>
Footer
This code will be constant for all pages
</div>

</body>
</html>

In order to reduce a number of repeated HTML (footer) we need to create a new one file: footer.scala.html

<div>
Footer
This code will be constant for all pages
</div>

And the last thing which we need to do is to change a little bit our index.scala.html

<html>
<head>
<title>Main page</title>
</head>

<body>

<div>
Header
</div>

<div>
<h1>Main page</h1>
<p>A lot of text here which can be changed from page to page.</p>
</div>

@footer()

</body>
</html>

That’s it. Short demonstration of Play! Framework’s template engine. For more information look at official Play site.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close