Is there any way to translate strings in Magento 2 to a specific locale (not necessarily the current one)?
Hypothetical example:
$translatedString = __("Some String", "de_DE");
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityIt's a bit more complicated - you'll need to emulate a store with that locale.
AppEmulation
and the AreaList
classes to the constructor of your class: /**
* @var \Magento\Store\Model\App\Emulation
*/
private $appEmulation;
/**
* @var \Magento\Framework\App\AreaList
*/
private $areaList;
public function __construct(
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Framework\App\AreaList $areaList
) {
$this->appEmulation = $appEmulation;
$this->areaList = $areaList;
}
$this->appEmulation->startEnvironmentEmulation($store->getId());
$area = $this->areaList->getArea(\Magento\Framework\App\Area::AREA_FRONTEND);
$area->load(\Magento\Framework\App\Area::PART_TRANSLATE);
$translatedText = __($text);
$this->appEmulation->stopEnvironmentEmulation();
The only way I managed to get the translation of specific locale is by using the function getDictionary
of class \Magento\Framework\App\Language\Dictionary
Here is the way I have used it:
1.) Declare
protected $dictionary;
2.) Use dependency inside the construct by
\Magento\Framework\App\Language\Dictionary $dictionary,
$this->dictionary = $dictionary;
3.) Now use the getDictionary() inside your function like:
$this->dictionary->getDictionary('de_DE')['Some String'];
This function returns associative array where key is phrase in the source code and value is its translation.
EDIT This solution works only for getting the translation from language pack. To have the correct translation which is used for the frontend we need to do app emulation. Please check the correct answer below by @Andreas
$this->dictionary->getDictionary('de_DE')['Some String'];
Dec 2, 2021 at 14:41
I had to use a combination of these two answers, for some reason the __($textToTranslate)
would not work within my helper class even though the text was there it wouldn't return the translation it just returned the text I was trying to translate, so I did it like this:
// in constructor add:
public function __construct(
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Framework\TranslateInterface $translate,
\Magento\Framework\App\AreaList $areaList
) {
$this->appEmulation = $appEmulation;
$this->areaList = $areaList;
$this->translate = $translate;
}
$this->appEmulation->startEnvironmentEmulation($store);
$area = $this->areaList->getArea(\Magento\Framework\App\Area::AREA_FRONTEND);
$area->load(\Magento\Framework\App\Area::PART_TRANSLATE);
$translation = $this->translate->getData()[$textToTranslate]