Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Play Framework: Template Include

DZone's Guide to

Play Framework: Template Include

· Java Zone
Free Resource

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

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 }}