Drupal 8 - Custom i18n

Example of how to implement custom translation in Drupal 8 modules.

Create PHP class implementing TranslationInterface


namespace Drupal\microatlas\Service;

use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Component\Utility\SafeMarkup;


class AtlasTranslator implements TranslationInterface {
	
	/**
	 * Translates a string to the current language or to a given language.	
	 */
	public function translate($string, array $args = array(), array $options = array()) {
		
		//TODO implement logic for selecting language
		$language = "cs";
		$translated = $this->getMessage($string, $language);
		
		if (empty($args)) {
			return SafeMarkup::set($translated);
		}
		else {
			return SafeMarkup::format($translated, $args);
		}				
		
	}
	
	public function formatPlural($count, $singular, $plural, array $args = array(), array $options = array()) {
		return null;
	}
	
	public function formatPluralTranslated($count, $translation, array $args = array(), array $options = array()) {
		return null;
	}
	
	public function getNumberOfPlurals($langcode = NULL) {
		return null;
	}
	
	private function getMessage($string, $language) {
		// define messages here
		$messages = array (
				"Micro Atlas" => array ("cs" => "Micro Atlas"),	
				"Back" => array ("cs" => "Zpět"),				
				
		);
		
		$message = null;
		if (array_key_exists ($string , $messages) && array_key_exists ($language, $messages[$string])) {
			$message = $messages[$string][$language];
		} else {
			$message = "*".$string;
		}
		
		return $message;
	}
		
}

Translation in Controller:


namespace Drupal\microatlas\Controller;

use Drupal\microatlas\Service\AtlasRepository;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\microatlas\Service\AtlasTranslator;

class AtlasController extends ControllerBase {
	
	public function __construct() {
		$this->setStringTranslation(new AtlasTranslator());
	}
	
	public function displayAtlas() {				
		$html = "

".$this->t("Micro Atlas")."

"; $output = array ( '#type' => 'markup', '#markup' => $html ); return $output; } }

Translation in Form:


class ImportForm extends FormBase {
	
	use StringTranslationTrait;
	
	public function __construct() {
		$this->setStringTranslation(new AtlasTranslator());
	}
	
	
	public function buildForm(array $form, FormStateInterface $form_state) {
	
	    $translated_string = $this->t("Micro Atlas");
		//...
	}
}