How to get translation in Umbraco by dictionary key

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.

Introduction

I assume that you have already defined translations in the Umbraco admin panel, if not just:

  • Login to Umbraco Backoffice
  • Go to the Translation section
  • Find the Dictionary section.
  • Create a dictionary item called "Forms.ContactForm.ThankYouMessage"
  • Fill in some text for all Languages (English, Polish, Russian, German) 

Umbraco Translation section - dictionary key and translations

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:

  • Find LanguageId (use your own method here, this is out of the scope of this article)
  • Get LocalizationService instance
  • Get Dictionary Item by Key ("Forms.ContactForm.ThankYouMessage")
  • Find the translation using the current language ID 
  • Once, the IDictionaryTranslation object was found - get the value using ".Value" property 

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;

Umbraco cms dictionary item

Umbraco cms translation

Bonus: How to get all languages in Umbraco?

Umbraco languages section

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();

LocalizationService instance - GetAllLanguages method

That's it, have a nice translation!

Comments
Leave a Comment