You expect to be able to send some data back to the View itself in web applications; this is quite straightforward with Play Framework. A Play View template is simply a text file that contains directives, web markup tags, and template tags. The View Template
files also follow standard naming conventions and they are placed in predefined directories within the Play project directory, which makes it easier to manage template files.
For Java, we need to take the following steps:
Run the
foo_java
application with Hot-Reloading enabled.Create the view file
products.scala.html
infoo_java/app/views/
. Add the contents of the view file:@(products: Collection[String]) <h3>@products.mkString(",")</h3>
Edit
foo_java/app/controllers/Application.java
by adding the following action:private static final java.util.Map<Integer, String> productMap = new java.util.HashMap<Integer, String>(); static { productMap.put(1, "Keyboard"); productMap.put(2, "Mouse"); productMap.put(3, "Monitor"); } public static Result listProducts() { return ok(products.render(productMap.values())); }
Edit
foo_java/conf/routes
by adding the following line:GET /products controllers.Application.listProducts
View the products page using a web browser:
http://localhost:9000/products
For Scala, we need to take the following steps:
Run the
foo_scala
application with Hot-Reloading enabled.Create the view file
products.scala.html
infoo_scala/app/views/
. Add the contents of the view file:@(products: Seq[String]) <h3>@products.mkString(",")</h3>
Edit
foo_scala/app/controllers/Application.scala
by adding the following action:private val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor") def listProducts() = Action { Ok(views.html.products(productMap.values.toSeq)) }
Edit
foo_scala/conf/routes
by adding the following line:GET /products controllers.Application.listProducts
View the products page using a web browser:
http://localhost:9000/products
In this recipe, we were able to retrieve a collection of data from the server side and display the contents of the collection in our View template. For now, we use a static collection of String objects to display in the View template instead of retrieving some data set from a database, which we will tackle in the upcoming recipes.
We introduced declaring parameters in View templates by declaring them in the first line of code in our view template and passing data into our View templates from the controller.