Scala PlayFrameWork 2.04: Get pages dynamically

So you want to generate a page dynamically parsing the url. You could use a map or some hard coded matches. But i prefer to use Java reflection inside Scala.

The code

The HTTP routing file: Routes

GET     /:page       controllers.Director.index(page: String)

The controller: Director.scala

package controllers

import play.api._
import play.api.mvc._
import views._
import models._
import java.util.Properties
import play.api.Play.current
import play.api.libs.iteratee.Enumerator
import java.lang.reflect.Method
import play.api.templates.Html
import models._
import play.api.http.Writeable

object Dynamic {

def render(keyword: String): Option[play.api.templates.Html] = {
 renderDynamic("views.html." + keyword)

def renderDynamic(viewClazz: String): Option[play.api.templates.Html] = {
 try {
 val clazz: Class[_] = Play.current.classloader.loadClass(viewClazz)
 val render: Method = clazz.getDeclaredMethod("render", classOf[String])
 val view = render.invoke(clazz, "test").asInstanceOf[play.api.templates.Html]
 return Some(view)
 } catch {
 case ex: ClassNotFoundException => Logger.error("Html.renderDynamic() : could not find view " + viewClazz, ex)

return None

object Director extends Controller with Secured {

def index(clazz: String) = Action {

 Dynamic.render(clazz) match {
 case Some(i) => Ok(i)
 case None => NotFound

As you can see i used reflection by using following method: “Play.current.classloader.loadClass(viewClazz)”. Now that i have the class, i can look up the declared methods (Notice the parameters) “clazz.getDeclaredMethod(“render”, classOf[String])”.
Then we are going to invoke it with the params by doing “invoke(clazz, “test”)”. Where “test” is the param of the method. And is actually the @title in the Play! html template below:

The view: template1.html.scala
 <div class="content">
 Here we put some content. .......



Scala scripting

Scala is a very powerful programming language which helps you to build scalable applications. But in some cases it comes handy to use Scala as a scripting language. For example executing from a cronjob.

The following code snippet shows you how easy it is to invoke a scala script in a bash script. I assume you have a lib dir where your classpatch jars exist.

lib=`dirname $0` ./lib
cp=`echo $lib/*.jar|sed 's/ /:/g'`
exec scala -classpath $cp $0 $@
// Say hello to the first argument
println("Hello " + args(0))

The first part is the executing part where we pass the first argument and a pointer to the next part.
Scala knows to execute the part beneath the “!#” and uses the given arguments.

Maybe when you installed Scala and you try to run your script like this:

servername]$ ./

And you get this error

Could not find a directory for temporary files

You need to open up the permissions for the following directory as root:

chmod 777 /tmp/scala-devel