NO.30 An Adobe Commerce developer is working on a Magento 2 instance which contains a B2C and a B2B website, each of which contains 3 different store views for English, Welsh, and French language users. The developer is tasked with adding a link between the B2C and B2B websites using a generic link template which is used throughout the sites, but wants these links to display in English regardless of the store view.
The developer creates a custom block for use with this template, before rendering sets the translate locale and begins environment emulation using the following code:
They find that the template text is still being translated into each stores language. Why does this occur?
The startEnvironmentEmulation() method resets the translation locale to the one of the emulated stores, which overrides the locale the developer has set when the order of setLocale() and startEnvironmentEmulation() is used as displayed above.
The correct way to achieve the desired result is to use the emulate() method to temporarily modify the translation locale. The following code shows how to do this:
PHP
$this->_translate->emulate(‘en_US’);
// Render the template
$this->_translate->revert();
This code will set the translation locale to English before rendering the template, and then revert the locale back to the default value after the template has been rendered.
The startEnvironmentEmulation() method is used to emulate a different store view or website. This can be useful for testing purposes, or for developing features that need to work in different environments.
The emulate() method is used to temporarily modify the translation locale. This can be useful for rendering templates in a specific language, or for testing features that need to work in different languages.