A usefull global Translate function for Razor templates in Umbraco

When implementing multi language templates CMS system Umbraco, you often need to use the dictionary
build into Umbraco to get translated words or phrases. In the Umbraco.Web.UmbracoHelper class a method exists which does the job from Razor: GetDictionaryValue(key).

It is useful and easy to use, but if the key is not defined an empty string is returned, that is not very useful. From using Dynamicweb CMS translate method, I am used to be able to specify a default value, which is used if the key has no value defined.

The global functions in Razor

Microsoft Razor has a folder App_Code which among other can be used to put global functions and helpers.
I have made a global function called “Translate”, which will has this signature

Translate(string key, string defaultValue = "”)

It takes from one to two arguments, the first is the key which is the Umbraco dictionary key you define in the back-end of Umbraco: Settings > Dictionary.

The defaultValue is optional, and should you choose not to use it, you will get a “*key” returned if the key was not defined in your dictionary (for the current language).

Using the function: Functions.Translate(..)

The function should be saved as Functions.cshtml inside the App_Code folder in your Umbraco project. The function will then become a global function and can be used from your Razor templates like this:

string translatedKey = Functions.Translate(“myKey”)

If the key is found in the Umbraco Dictionary, that value will be placed in the “translatedKey”. If the key is not found for the current language, the value of “translatedKey” will become: “*myKey”. It is then easy to see on the website that a key is required for “myKey”.

The code – find it on gist.github.com

You can see the code below, or you can find it on my gist page at Github.

US

Leave a Reply