Sitecore’s core functionality comes with the ability to localize content in multiple languages. This is done via the native language versioning of content items. Websites that leverage this multi-lingual capability typically provide a mechanism to switch between languages. Getting the context language that a user has selected is easy in Sitecore but it takes a bit more work to get the Iso code for the language. It’s nice to get the Iso code for the selected language so the language can be switched using Sitecore’s “sc_lang” query string key.
First, get the context language item. This is not merely the context language, but rather the context language definition item located under
LanguageManager to get the GUID of the Language item based on the context language. From this, you can get the actual language item from the context database:
ID contextLanguageId = LanguageManager.GetLanguageItemId(Sitecore.Context.Language, Sitecore.Context.Database);
Item contextLanguage = Sitecore.Context.Database.GetItem(contextLanguageId);
Next, you can get the “Regional Iso Code” field if one is set for the language. The out-of-the-box English language does not have a “Regional Iso Code” so fallback to the “Iso” field if necessary:
string iso = contextLanguage["Regional Iso Code"];
iso = contextLanguage["Iso"];
Now you’ll end up with something like “en” or “es-ES” for English and Spanish (Spain) respectively.
What can you use those Iso codes for? Good question. Sitecore provides a native way to switch the context language. Simply set the Iso code in the query string for the
"sc_lang" query string key. This will change the context language. For example, you might want to create a language selector tool which given the languages defined in Sitecore switches the query string with the new Iso code (or Regional Iso Code). You can then use the context language’s Iso code to update your language selector tool to identify the current language.