May 20, 2019 in Drupal 8, Snippets, Multilanguage

The page callback system in drupal 8 is considerably different from drupal 7. This snippet shows you how to show a title depending on your language.

First, we setup a custom module and add a routing file: mymodule.routing.yml:

mymodule.custom_page:
  path: '/my-custom-page'
  defaults:
    _title_callback: '\Drupal\mymodule\Controller\customPageController::getTitle'
    _controller: '\Drupal\mymodule\Controller\customPageController::render'

Then in a map src/Controller add a file customPageController.php:

namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;

class customPageController extends ControllerBase {
  public static function render() {
    return [
      '#markup' => '<p>Hello world!</p>'; // the content of your page
    ];
  }

  /**
   * Returns a page title.
   */
  public function getTitle() {
    // Get current language code
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    switch($language) {
      case 'nl':
        $title = 'Titel in dutch';
        break;
      case 'en':
        $title = 'Title in english';
        break;
    }
    return  $title;
  }

}