I just started messing around with Play 2. I recently learned how to create a model (User) and how to show it in the view (please let me know if there’s any bad practice):
models/User.scala:
package models
case class User(id: Long, name: String)
object User {
var user = User(
id = 1L,
name = "Mark"
)
def greeting = TODO
}
controllers/Application.scala:
package controllers
import play.api._
import play.api.mvc._
import models.User
object Application extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
def hello = Action {
Ok(views.html.hello(User.user))
}
}
hello.scala.html:
@(user: User)
@main("Welcome to Play 2.0") {
<h2>@user.id</h2>
<h3>@user.name</h3>
}
Now, I want to display the output of a function in the view.
How to accomplish that?
Let’s use another view (tag) which as you probably know is also just a Scala function:
/app/views/tags/userName.scala.html
So you can use the
userNamefunction in yourindexviewDe facto the same you can also use functions from your models and controllers by just specyfying it as:
And if your class isn’t placed in
controllersormodelspackages (which are imported into the views by default) you just need to use full qualified path: