Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering play framework for scala

You're reading from  Mastering play framework for scala

Product type Book
Published in May 2015
Publisher
ISBN-13 9781783983803
Pages 274 pages
Edition 1st Edition
Languages
Author (1):
Shiti Saxena Shiti Saxena
Profile icon Shiti Saxena

Table of Contents (21) Chapters

Mastering Play Framework for Scala
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
1. Getting Started with Play 2. Defining Actions 3. Building Routes 4. Exploring Views 5. Working with Data 6. Reactive Data Streams 7. Playing with Globals 8. WebSockets and Actors 9. Testing 10. Debugging and Logging 11. Web Services and Authentication 12. Play in Production 13. Writing Play Plugins Index

Chapter 4. Exploring Views

Views are an essential part of an application, or, in cases where interaction is minimal, they are the means to show what an application is capable of. They have the power to increase the number of end users or discourage them completely. Views that enhance the user experience are always preferred over those that are as complicated as a maze, through which the user struggles to perform a simple task. They act as a deciding factor in an application's success.

In this chapter, we will cover the following topics:

  • Building views using Twirl

  • Generating Form

  • Internationalization

  • Templating Internals (covers basics of how Twirl works)

Diving into Scala templates


A Twirl template is composed of parameters and content. The following figure shows the components of a login page template called login.scala.html:

Note

The parameters must be declared first since they are used as the parameters of the apply method of the generated template object. For example, for the main.scala.html template, shown in the preceding code, the apply method will be:

def apply/*1.2*/(title: String)(content:play.api.twirl.Html):play.api.templates.HtmlFormat.Appendable = {...}

The template content can be HTML as well as Scala code.

For example, let's look at some defaultpages (accessible through the object views.html.defaultpages) bundled along with Play. The default view for this action is not implemented; todo.scala.html has no template parameters and has plain HTML for its content. It is defined as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>TODO</title>
    <link rel="shortcut icon" href="data:image/png;base64...

Generating forms


Forms are important in situations where the application requires input from users, for example, in the case of registration, login, search, and so on.

Play provides helpers to generate a form and wrapper classes to translate the form data into a Scala object.

Now, we'll build a user registration form using the form helper provided by Play:

@helper.form(action = routes.Application.newUser) {
  <label>Email Id
  <input type="email" name="email" tabindex="1" required="required">
        </label>

        <label>Password
          <input type="password" name="password" tabindex="2" required="required">
        </label>

        <input type="submit" value="Register" type="button">
    }

Here, @helper.form is a template provided by Play, which is defined as follows:

@(action: play.api.mvc.Call, args: (Symbol,String)*)(body: => Html)

<form action="@action.url" method="@action.method" @toHtmlArgs(args.toMap)>
  @body
</form>

We...

Internationalization


Due to the wide reach of the Internet, it is now possible to communicate and interact with people from diverse locations. An application that communicates with users in one specific language restricts its user base through the use of only that language. Internationalization and localization can be used to cater to user groups from various regions by removing barriers that arise due to the use of a particular language only.

Now, let's build a simple view, which allows us to ask a question. The views/index.scala.html view file will be similar to the following:

@(enquiryForm: Form[(String, Option[String], String)]) 

@import helper._ 

@main("Enquiry") { 

    <div> 
        <h2>Have a question? Ask Us</h2> 

        @form(routes.AppController.enquire) { 

            @enquiryForm.globalError.map { error => 
                <p> 
                    @error.message 
                </p> 
            } 

            <label for="emailId">...

Scala templating in Play


Play supports the use of Scala code within views and also provides a couple of helper methods to ease the process of defining a view.

We've created different views till now. Let's see how they are actually rendered. Consider the view for the Task Tracker app we saw in Chapter 1, Getting Started with Play.

@(tasks: List[Task], taskForm: Form[String])

@import helper._

@main("Task Tracker") {
 
    <h2>Task Tracker</h2>

    <div>
    @form(routes.TaskController.newTask) {

        @taskForm.globalError.map { error =>
            <p class="error">
                @error.message
            </p>
        }
        <form>
            <input type="text" name="taskName" placeholder="Add a new Task" required>

            <input type="submit" value="Add">
        </form>
    }
    </div>
    <div>
        <ul>
        @tasks.map { task =>
            <li>
                @form(routes.TaskController...

Troubleshooting


Here are a few issues we can come across while using a Play view:

  • The form is not submitted when you click on Submit and no errors are displayed using globalErrors.

    There may be a situation where a particular required field is missing or there is a typo in the name of the field. It will not be shown in globalErrors but if you attempt to display the error for an individual field, error.required will show up for the missing field.

  • Do we need to use Twirl templates for the application's views?

    No, Play does not force developers to use Twirl templates for the views. They are free to design the views in whichever way they find easy or comfortable. For example, this can be done by using Handlebars, Google Closure templates, and so on.

  • Does this affect the performance of the application in any way?

    No, unless there are no performance flaws in your view definitions, plugging it in a Play application will not affect the performance. There are projects that use the Play server for their...

Summary


In this chapter, we saw how to create views using Twirl and the various helper methods provided by Play. We have built different kinds of views: reusable templates or widgets and forms. We also saw how to support multiple languages in our Play application using the built-in i18n API.

In the next chapter, we will cover how to handle data transactions available in Play, and also gain insights into how to effectively design your models.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Mastering play framework for scala
Published in: May 2015 Publisher: ISBN-13: 9781783983803
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}