2

Is there a way to get the language from a routeMatch in Drupal 8?

E.g. if I do:

$route_match = \Drupal::routeMatch();

Currently I can't find any language information in the returned object. It looks like as if all language information has been stripped out, and the route object know's nothing about the language it is in.

I've looked into using the language manager, but can't find a way to combine this with the routeMatch class.

Scenario: I'm writing my own AccessInterface class, and want to hide entities from certain languages. I need the information of the language for the route (and not the site's current language).

5
  • Hav you tried $language = \Drupal::languageManager()->getCurrentLanguage()->getId();?
    – Robin
    Mar 28, 2017 at 16:22
  • @robin that's getting the current language. This may not nexcesarily be the language of the route/URL. E.g. We might be linking to a German translation from an English node.
    – leon.nk
    Mar 28, 2017 at 21:19
  • If you link to an German translation and the user clicks the link, the current language will be German... I don't see the problem? The URL will change to /de/node/2
    – Robin
    Mar 29, 2017 at 6:36
  • The user hasn't clicked yet. Drupal is checking whether the user has access to /de/node/2 but the current page is /node/2
    – leon.nk
    Mar 29, 2017 at 6:39
  • For more context, here's the issue I'm trying to resolve: drupal.org/node/2864679
    – leon.nk
    Mar 29, 2017 at 6:44

1 Answer 1

1

I actually had the same problem with a Drupal 8 site.

I know this is unlikely to sound like a problem, but I can think of at least one situation (the situation I am in!) where it is.

We have the CMS setup so that the admin interface is in the users preferred langauge (a request by the client) so they can copy-paste translated content in whilst keeping the admin interface in a language they can understand.

However this creates confusion, as \Drupal::languageManager()->getCurrentLanguage() returns the langauge the admin system is using, not the lanuage the content is in.

The easiest way I found around this was to do the following:

$node = \Drupal::routeMatch()->getParameter('node'); $currentLanguage = $node->langcode->value;

(if anyone is curious as to why $node->langcode->value works, this question has some good answers: How to get the property of a content object in Drupal 8)

This literally gets the current node you've viewing, and then the language the node is displaying in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.