Book Image

Play Framework Cookbook

By : Alexander Reelsen
Book Image

Play Framework Cookbook

By: Alexander Reelsen

Overview of this book

<p>The Play framework is the new kid on the block of Java frameworks. By breaking with existing standards the play framework tries not to abstract away from HTTP as most web frameworks do, but tightly integrates with it. This means quite a shift for Java programmers. Understanding these concepts behind the play framework and its impact on web development with Java are crucial for fast development of applications.<br /><br />The Play Framework Cookbook starts where the beginner documentation ends. It shows you how to utilize advanced features of the Play framework &ndash; piece by piece and completely outlined with working applications!<br /><br />The reader will be taken through all layers of the Play Framework and provided with in-depth knowledge from as many examples and applications as possible. Leveraging the most from the Play framework means to think simple again in a java environment. Implement your own renderers, integrate tightly with HTTP, use existing code, improve site performance with caching and integrate with other web services and interfaces. Learn about non-functional issues like modularity or integration into production and testing environments. In order to provide the best learning experience during reading Play Framework Cookbook, almost every example is provided with source code, so you can start immediately to integrate recipes into your own play applications.</p>
Table of Contents (16 chapters)
Play Framework Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Further Information About the Play Framework
Index

Defining your own views


After getting a closer look at controllers and models, the missing piece is views. Views can essentially be anything: plain text, HTML, XML, JSON, vCard, binary data such as images, whatever you can imagine. Generally speaking, the templating component in Play is kept very simple. This has several advantages. First, you are not confronted with a new tag library, like you are in JSF with every new component. Second, every web developer will dig his way through this templating language quite fast. Third, the templating language is very nice and also very easy to extend. Even though the template language is based on Groovy and uses some Groovy expressions, there is absolutely no need to have any deep knowledge in Groovy. Even though you can use Groovy expressions, there is absolutely no need for it.

In this example, we will put together a small view showing our user entity.

How to do it...

The first step is to get the user inside the controller and allow it in the view to be used. Edit app/controllers/Application.java and change the showUser() method to this:

public static void showUser(Long id) {
        User user = User.findById(id);
        notFoundIfNull(user);
        render(user);
}

After that create an HTML template file in ./app/views/Application/showUser.html:

#{extends 'main.html' /}
#{set title:'User info' /}

<h1>${user.login}</}</}</h1>

Send <a href="mailto:${user.email}">}">}">mail</a>

How it works...

Though again only a couple of lines have been written, a lot of things have happened. Beginning with the name and path of the template location, it is just the name of the class (including the package, which the controller does not have in this case) and its method name appended with a file format. Of course, you can change it, but this way it is pretty easy to understand which view code belongs to which controller action.

Regarding the controller logic all that has been done is to query the database for the user with a specific ID (the one specified in the URL) and to return a HTTP 404 error, if the returned object is null. This eliminates the nasty null checks from your code to keep it as clean as possible. The last part triggers the rendering. The argument handed over (you can choose an arbitrary amount of arguments) can be referenced in the HTML template under the name you put in the render() method. If you used render(userObj) you could reference it as userObj in the template.

The template contains lots of information in the four lines of code. First, Play template specific tags always use a #{} notation. Second, Play templates support some sort of inheritance with the #{extends} tag, as the main.html has been chosen here as a template into which the rest of the code is embedded. Third, you can set variables in this template, which are parsed in the main.html template, like the variable title, which is set in line two. Lastly you can easily output fields from the user object by writing the name of the object inside the template and its field name. As already done before, the field is not accessed directly, but the getter is called.

There's more...

Templating is covered fairly well in the documentation and in the example, so be sure to check it out.

Check out more possible template tags

There are more than two dozen predefined tags which can be used. Most of them are pretty simple, but still powerful. There is a special #{a} tag for creating links, which inserts real URLs from a controller action. There are of course #{if} structures and #{list} tags, form helper tags, i18n and JavaScripts helpers, as well as template inheriting tags and some more:

http://www.playframework.org/documentation/1.2/tags

Check out more predefined variables

There are some variables which are always defined inside a template, which help you to access data that are always needed without putting it explicitly into the render call. For example, request, session, params, errors, out, messages, flash, and lang. You can have a look at the documentation for more details:

http://www.playframework.org/documentation/1.2/templates#implicits

Supporting multiple formats

There are also more predefined render() methods with different output formats than HTML defined. Most known are renderText(), renderXML(), renderJSON(), and renderBinary() for images. Be aware that all of these methods do not use templates, but write out the result directly to the client without invoking any template specific code.

See also

It is very easy to write your own tags, so be sure to follow the next recipe as well as get some information about mixins, which allows you to define some more logic for displaying data without changing it in the model; for example, replacing the last digits with XXX for privacy issues.

Furthermore, a recipe with an own renderRSS() is shown as last recipe in Chapter 2, which is about controllers.