I'm trying to add a language switcher to a Drupal 8 site menu (it's switching between English and Spanish). I have the links working when logged in as admin but they're not shown for anonymous users, even though the language switcher block displays fine, as well as adding a language switcher through twig. However, I'd really like to get this working and be able to add it to menus through a custom module.
As an anonymous user I am able to view the translated content (by clicking the Default Drupal language switcher options) but these links that are created are not rendered.
Here's my code for the custom module:
MYMODULE.links.menu.yml
MYMODULE.switch:
class: Drupal\MYMODULE\Plugin\Menu\MenuLanguageLink
menu_name: MENUNAME
route_name: '<current>'
options:
attributes:
hreflang: 'en'
MYMODULE.switch_2:
class: Drupal\MYMODULE\Plugin\Menu\MenuLanguageLink
menu_name: MENU2NAME
route_name: '<current>'
options:
attributes:
hreflang: 'es'
/src/Plugin/Menu/MenuLanguageLink.php:
<?php
/**
* @file
* Contains \Drupal\MYMODULE\Plugin\Menu\LanguageSwitchController.
*/
namespace Drupal\MYMODULE\Plugin\Menu;
use Drupal\Core\Menu\MenuLinkBase;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MenuLanguageLink extends MenuLinkBase implements ContainerFactoryPluginInterface {
/** @var array Available languages */
protected $languages = [];
/**
* {@inheritdoc}
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
LanguageManagerInterface $language_manager
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->languages = $language_manager->getLanguages();
}
/**
* Dependency injection.
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition
) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function updateLink(array $new_definition_values, $persist) {
return $this->pluginDefinition;
}
/**
* {@inheritdoc}
*/
public function getOptions() {
$options = parent::getOptions();
$langcode = $options['attributes']['hreflang'];
if (isset($this->languages[$langcode])) {
$options += ['language' => $this->languages[$langcode]];
}
return $options;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
$langcode = $this->getOptions()['attributes']['hreflang'];
if ($langcode == 'es') {
return 'Español';
} else {
return $this->languages[$langcode]->getName();
}
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('Switch Language');
}
}