SFCC provides a built-in system to manage different aspects of the data in multiple languages. But sometimes, you want to show something in a specific locale outside the current session context. How can this be done?
For those in a hurry:
// Store the current situation to re-set it later var currentLocale = request.getLocale(); request.setLocale('xx_XX'); /* * Do your thing */ // Reset the request language to the original request.setLocale(currentLocale);
How does it work?
Ultimately, the solution is quite simple – the Salesforce B2C Commerce Cloud systems take care of the “hard stuff” for us. We have to tell it at the right time in what language we want our object to be returned.
The request takes point
The system will look at the current request’s language preference (or setting) whenever an object is fetched through its appropriate function (and it has localised attributes).
The request is always available in every context under the global variable “request“. It is always there, no matter where you are:
- Storefront request
- Business Manager request
- Job Step
- OCAPI / SCAPI Hook
Changing the language before fetching data
To fetch data in a specific language, we must modify the current request before doing the “get”. If we want to fetch an attribute in a specific language, we can do something like this:
var ProductMgr = require('dw/catalog/ProductMgr'); var product = ProductMgr.getProduct('my_sku'); request.setLocale('zh_CN'); var cnName = product.name; request.setLocale('en_US'); var enName = product.name;
Restoring the locale if necessary
Remember to restore the original language after the data has been fetched in the alternate language. If this is forgotten, all the data fetched after will be in the incorrect language!
Some might ask, why would you need to do such a thing? Well, there are a few reasons which will cause you to resort to fiddling with the request:
- Fetching a content asset in a different language, a language selection popup, for example.
- Generating a single-file feed with multiple languages
- Fetching a translation from a resource bundle in a specific language
- … and many more
What about the Composable Storefront?