In this blog, I will demonstrate how your application can support different languages using Play Framework 2.6.0

default.message = Play Framework Example
- request.messages return the instance of Messages, using implicit MessagesApi.
- request.lang returns the preferred Lang, using implicit MessagesApi
- result.withLang(lang: Lang) is used to set the language for future request by storing it in the cookie.
- result.clearingLang is used to discard the language cookie set by withLang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MySupportController @Inject()(component: ControllerComponents, | |
langs: Langs) extends AbstractController(component) with I18nSupport { | |
val lang: Lang = langs.availables.head | |
implicit val messages: Messages = MessagesImpl(lang, messagesApi) | |
def index = Action { implicit request => | |
val messages: Messages = messagesApi.preferred(request) // get the messages for the given request | |
val message: String = messages("default.message") | |
Ok(views.html.index(message)) | |
} | |
def homePageInFrench = Action { | |
Redirect("/").withLang(Lang("fr")) // set french language in the Play's language cookie for future requests | |
} | |
def homePageWithDefaultLang = Action { | |
Redirect("/").clearingLang // discarding the language cookie set by withLang | |
} | |
} |
4. Messages with Twirl Template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@(message: String, style: String = "scala")(implicit messages: MessagesProvider) | |
@defining(play.core.PlayVersion.current) { version => | |
<section> | |
<div class="wrapper"> | |
@if(messages.messages.lang.language.equals("en")) { | |
<a class = "button" href="@routes.MySupportController.homePageInFrench()">fr</a> | |
} else { | |
<a class = "button" href="@routes.MySupportController.homePageWithDefaultLang()">en</a> | |
} | |
</div> | |
</section> | |
<div id="content" class="wrapper doc"> | |
<article> | |
<h1>@message</h1> | |
<h2>@messages.messages("home.title")</h2> | |
</article> | |
</div> | |
} |
Here Twirl templates take MessageProvider, and it is assumed that a MessageProvider is passed into the template as an implicit parameter.
Well explained
Reblogged this on Play!ng with Scala.