How to get translation in Umbraco by dictionary key

This article will demonstrate how to get translation in Umbraco Cms using LocalizationService for a given dictionary key.

Defining translations in the Backoffice

At this stage, we need some data to work.

  • Login to the Umbraco Backoffice panel.
  • Go to the Translation section.
  • Find the Dictionary section (left panel).
  • Create a dictionary item called “Forms.ContactForm.ThankYouMessage”.
  • Fill in some text for all Languages (English, Polish, Russian, German) .
Umbraco Dictionary Key
Umbraco Dictionary Tree
Umbraco Dictionary Key And Translations
Umbraco Dictionary item with 4 languages

Once the dictionary item is ready, we can move on.

How to get translation in Umbraco CMS for the given key?

You should take the following steps:

  • Find the desired language identifier (integer) – you can view a list of all languages under /umbraco#/settings/languages/overview
  • Get LocalizationService instance
  • Execute LocalizationService.GetDictionaryItemByKey(key) method passing the string key (“Forms.ContactForm.ThankYouMessage”)
  • Find the translation for the given LanguageId
  • Once, the IDictionaryTranslation object was found – you can retrieve the value with “.Value” property 

Quick 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;

Example with fallback

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;
Thankyou Message Dictionary Item
Debugging IDictionaryItem
Thank You Message Translation
Debugging IDictionaryTranslation

Listing all languages in Umbraco programmatically

Umbraco Languages Section
Umbraco Panel: languages overview – /umbraco#/settings/languages/overview

The simplest approach to list all defined languages is to use the LocalizationService class.

With given LocalizationService instance – use the GetAllLanguages method as follows:

var allLanguages = Services.LocalizationService.GetAllLanguages();
Localizationservice Getalllanguages
Debugging Umbraco languages

That’s it, have a nice translation!

Similar Posts