How to get translation in Umbraco by dictionary key
Table of contents
In this short article, I am going to show the steps needed to get translation in Umbraco CMS by dictionary key using LocalizationService.
It's really easy to play with languages in Umbraco CMS and create a multilingual website.
Defining translations in the Backoffice
I assume that you have already defined translations in the Umbraco admin panel, if not just:
Once the dictionary item is there, we can move on.
How to get translation in Umbraco CMS by dictionary key?
You should take following steps:
Simple example
var currentLanguageId = 1;
IDictionaryItem thankYouMessageDictionaryItem = Services.LocalizationService.GetDictionaryItemByKey("Forms.ContactForm.ThankYouMessage");
IDictionaryTranslation thankYouMessageTranslation = thankYouMessageDictionaryItem.Translations.FirstOrDefault(x => x.LanguageId == currentLanguageId);
string thankYouMessage = thankYouMessageTranslation.Value;
Full example
const string defaultFallbackMessage = "Thank you for your message! We will contact you soon";
// helper method to find the language - use your own implementation
var currentLanguageId = SiteLanguageHelper.GetCurrentLanguage(url);
IDictionaryItem thankYouMessageDictionaryItem = Services.LocalizationService.GetDictionaryItemByKey("Forms.ContactForm.ThankYouMessage");
IDictionaryTranslation thankYouMessageTranslation = thankYouMessageDictionaryItem.Translations.FirstOrDefault(x => x.LanguageId == (int)currentLanguageId);
string thankYouMessage = thankYouMessageTranslation != null ? thankYouMessageTranslation.Value : defaultFallbackMessage;
Bonus: How to list all languages in Umbraco?
The best way to list all defined languages is to use LocalizationService.
With given LocalizationService instance - use the GetAllLanguages method as follows:
var allLanguages = Services.LocalizationService.GetAllLanguages();
That's it, have a nice translation!
Comments
Leave a Comment