[英]scala play2.5 how to pass global messages to template
I have a play2.5 scala project and I want to pass a global message from the controller for example in case an error happened. 我有一个play2.5 scala项目,例如,如果发生错误,我想从控制器传递全局消息。 How can I achieve this without using the form global message.
我如何不使用表单全局消息来实现这一点。
For example in the handleRegisterError method I would like to throw an global error message that would show on the top off the page. 例如,在handleRegisterError方法中,我想抛出一条全局错误消息,该消息将显示在页面顶部。
What is the best approach to this? 最好的方法是什么?
I'm using twirl templates 我正在使用旋转模板
def registerUser = Action.async { implicit request =>
RegisterForm.form.bindFromRequest.fold(
formWithErrors => {
Future.successful(BadRequest(views.html.register(formWithErrors)))
},
formData => {
registerUserService.registerUser(formData).map{ insertedId =>
Ok(views.html.index(""))
}
.recover {
case cause => handleRegisterError(cause)
}
})
}
def handleRegisterError(cause: Throwable)(implicit req: RequestHeader) : Result = {
cause match {
case dae: DataAccessException =>
//add an error message here
BadRequest(views.html.register(RegisterForm.form))
case _ =>
BadRequest(views.html.register(RegisterForm.form))
}
}
You should be able to use Redirect
with the message attached to Flash
scope 您应该能够将
Redirect
与附加到Flash
作用域的消息一起使用
Redirect(views.html.register(RegisterForm.form)).flashing("error" -> "Oops, you've got an error")
Add RequestHeader
as a template parameter and render the error message if defined. 将
RequestHeader
添加为模板参数,并在定义后呈现错误消息。
@(form: Form[RegisterForm])(implicit request: RequestHeader)
@request.flash.get("error").map { message =>
<div>@message</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.