On my Drupal 8 website I have a content type "Video" which has an "Embed Code" field. Later the user is able to watch the video inside the platform. The value for this field usually looks like this:

<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/some_link" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Is there a way to change the source link based on the language of the browser? So for example when the user browser's language is set to "FR", then I would like to append to the emded link the french captions, so that the link looks following ?



This is the plugin what also core using for browser language negotiation. You can have a closer look what the plugin exactly does: \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser

The code

$language_negotiation_method_manager = $this->container->get('plugin.manager.language_negotiation_method');
$plugin_id = LanguageNegotiationBrowser::METHOD_ID;
/** @var \Drupal\language\LanguageNegotiationMethodInterface $language_negotiation_method */
$language_negotiation_method = $language_negotiation_method_manager->createInstance($plugin_id);
$request = $this->container->get('request_stack')->getCurrentRequest();
$browser_langcode = $language_negotiation_method->getLangcode($request);

This will either give you back a valid language code or FALSE if the negotiation was unsuccessful.

Regarding the dependencies

  1. $container is only used as an example to show which services are being used.
  2. Request is always present as an argument when you are in a controller.
| improve this answer | |
  • This, and hook_preprocess_field and probably also a custom cache tag to round it up. :) – leymannx Jun 25 '19 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy