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 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 CMS Dictionary Tree

Umbraco Translation section - dictionary key and translations

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;

Umbraco cms dictionary item

Umbraco cms translation

Listing all languages in Umbraco programmatically

Umbraco languages section

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 instance - GetAllLanguages method

That's it, have a nice translation!

Comments
Leave a Comment