Play framework : Setting Lang in a helper.form in a scala view
-
12-12-2019 - |
Question
I've got the following code in a view :
@(lang:Lang)...
...
<div>
...
@helper.form(action = routes.item.add) {
<p>@helper.inputText(myItem("name"))</p>
...
}
...
</div>
In my internationalization files, i have entries for name
.
e.g. :
- in
messages.en
:name=Name
- in
messages.fr
:name=Nom
The view is always rendered with the french label for this inputText
and I don't know how to change for another langage, e.g. using the global parameter lang
defined in my view.
I was looking for some solutions like : @helper.form(action = routes.item.add, lang)
or the same kind of code at inputText
level.
Solution 2
My solution :
@(lang:Lang)...
@import play.i18n._
@translate(text: String) = @{
Message.get(lang, text)
}
...
<div>
...
@helper.form(action = routes.item.add) {
<p>@helper.inputText(myItem("name"), '_label -> translate("name"))</p>
...
}
...
</div>
In Play, it's possible to add attribute to the forms with the '_
convention. I have overriden the label using this by applying my own translate function.
OTHER TIPS
Are you using Scala
or Java
? With Scala you can set a implicit language. But for Java this is not easy as in Play 1.2.4:
Lang.set(...) or .change()
This will be solved in 2.1: https://play.lighthouseapp.com/projects/82401/tickets/174-20-i18n-add-ability-to-define-implicit-lang-for-java-api
See previous discussion in Google Groups: https://groups.google.com/forum/?fromgroups#!topic/play-framework/dE1SPBaTM6w
Is you use scala have a look at post: i18n error: controller and templates uses different implicit languages