Over a million developers have joined DZone.

Play Framework: Template Include

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}