Adriano
Adriano

Reputation: 20041

Scala (2.11.1) & play framework (2.x) if statement with variable in Flash scope

Heads up: I'm a total newbie to Play! framework & Scala

In my controller, I set a variable (of type String) in the flash scope

 flash("success", "Well done!");

In the Scala template, let's call it pageName.scala.html , I can display its value such as:

 @flash.get("success")

But I want to add some html around it: only show the relevant HTML & flash variable value when necessary. Here is some pseudo-code describing what I'd like to do:

 if successVarInFlashScope is not empty
   <div class="global-notification__inner">
     <div class="global-notification__msg">@flash.get("success")</div>
   </div>
 end if

I tried a few different things but no luck.

I also looked into the Play framework documentation & on StackOverflow but no luck either.

Resources:

Upvotes: 2

Views: 242

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Scala:

The get method on Flash returns an Option[String] that you can map:

@flash.get("success").map { msg =>
   <div class="global-notification__inner">
     <div class="global-notification__msg">@msg</div>
   </div>
}

Java:

Http.Flash in Play Java extends java.util.HashMap, so get will either return String or null. Unfortunately, we can't be as elegant as the above code in Java, so an if will have to do.

if(@flash.get("success") != null) {
   <div class="global-notification__inner">
     <div class="global-notification__msg">@flash.get("success")</div>
   </div>
}

Or if(@flash.containsKey("success"))

Upvotes: 3

Related Questions