PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

[FIXED] How do I get the current language in Play Framework 2.7

 April 14, 2022     migration, playframework, translation     No comments   

Issue

I'm migrating from Play Framework 2.6 to version 2.7.

In this version, they deprecated a lot of stuff that I was using. One of them is the Lang methods as you can see in their migration page: https://www.playframework.com/documentation/2.8.x/JavaHttpContextMigration27#Lang-and-Messages-methods-in-Http.Context-deprecated

Since I mainly use Play as a plain back-end API, I'm not using any views but for some calls, I need to know what is the current language so I can return translated values.

The problem is that I can't find any ways to get the current language. All the examples show ways to change/clear the current language or how to use it in Views but I just want to query the current language.

For example, my old code:

play.api.i18n.Lang lang = ctx().lang();

Or this:

lang().code()

How can I achieve a similar result with Play 2.7 + ? Thanks


Solution

You may get it by injecting MessagesApi.

Like this in a controller (written directly in this wysiwyg, not tested):

@Inject
private MessagesApi messagesApi;

public Result index(Http.Request request) {
    Lang currentLang = messagesApi.preferred(request).lang()
    String langStr = currentLang.code();

    return ok();
}


Answered By - Eirik Finvold
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing