Pages

Wednesday, January 4, 2012

Using the Sitecore Dictionary

The Sitecore Dictionary is very useful when you want controls to display content in different languages depending on the current language (Sitecore.Context.Language).

Although the use of the dictionary looks very straight forward, I initially bumped into a small problem. My problem was that no matter what dictionary item I added, it did not display the right translation. In the end we were able to find out you need to publish the site to see the translations, even when you’re an administrator and working in the development environment.

To help you get started using the dictionary without any problems, I will describe the steps you need to make.

Step 1. Open the content editor and go to the dicotionary in the item tree. Add an item (dictionary entry) to the dictionary and make sure the selected database is the master database. Fill in the key (for every language the same) and phrase (depending on you current selected language).
If you have a dynamic part in your phrase, you can use {0} to replace that part of the content.

To organize the entries you can add folders in the dictionary, for example a folder named A for all entries starting with an A etc.

Step 2. In your code go to the place where you want to display the content. The easiest way to display the content is using
Translate.Text([key])
but, you can also use the dictionary for displaying dynamic content by using arguments/parameters. In this case you have to use the
Translate.Text([key], [parameters])

Example
This example is a custom user control that display a literal. The properties for the literal are a key and parameters. With these properties you can get the translation for the current language. As you can see in the example it is even possible to display multiline content from the dictionary, you will only have to parse it to html.

using System;
using System.Web.UI;
using Sitecore.Globalization;

namespace SitecoreSolutions.layouts.UserControls
{
 public partial class LocalizedLiteral : UserControl
 {
  public string Key { get; set; }
  public object[] Parameters { get; set; }

  protected override void OnLoad(EventArgs e)
  {
   base.OnLoad(e);

   if(Key!= null)
    LiteralLocalizedValue.Text = Transform(Parameters == null ? Translate.Text(Key) : Translate.Text(Key, Parameters));
  }

  public string Transform(string data)
  {
   data = data.Replace("\r\n", "<br/>");

   return data;
  }
 }
}

Step 3. In order to view the translations/content you always have to publish the dictionary, and voila there is your content.


1 comment: