[Play 2.5.0] How to use new MessagesApi ?

1,013 views
Skip to first unread message

Kamil

unread,
Mar 29, 2016, 3:38:08 PM3/29/16
to play-framework
The documentation shows how to use static Messages.get (https://www.playframework.com/documentation/2.5.x/JavaI18N#Externalizing-messages) but since Play 2.5 this is deprecated.

How can I use new MessagesApi instead?
Could you please provide me with any example?

Thank you in advance,
Kind regards
Kamil

Maxim Valyanskiy

unread,
Mar 29, 2016, 4:24:27 PM3/29/16
to play-framework
You need to mix I18nSupport trait to your controller or service.

Look at migration guide for Play 2.4, it has an example:



вторник, 29 марта 2016 г., 22:38:08 UTC+3 пользователь Kamil написал:

Geert Vanheusden

unread,
Mar 29, 2016, 4:37:36 PM3/29/16
to play-framework
Hi Kamil,

In Java you can achieve this by using the following code:

import com.google.inject.Inject;
import play.i18n.Messages;
import play.i18n.MessagesApi;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;

public class HomeController extends Controller {

   
private MessagesApi messagesApi;

    @Inject
    public HomeController(MessagesApi messagesApi) {
       
this.messagesApi = messagesApi;
    }

   
public Result index() {
       
Messages messages = messagesApi.preferred(request());
        return ok(index.render(messages.at("test")));
    }

}

Or you can use:

public Messages preferred(Collection<Lang> candidates)

if you want to specify the languages yourself.

Regards,

Geert

Kamil

unread,
Mar 29, 2016, 7:27:15 PM3/29/16
to play-framework
Thanks Geert!
That's exactly what I needed.

I was confused, because Eclipse shows me that method "preferred" requires "RequestHeader" as a parameter, so I tried to pass request()._underlyingHeader()
Reply all
Reply to author
Forward
0 new messages