DEV Community

Morten Hartvig
Morten Hartvig

Posted on

Replacing placeholders in Umbraco's dictionary items

Umbraco's dictionary feature is really cool as it allows editors to control the text you have on buttons, in form labels and other places on your website, removing the need to involve a developer in order to change simple sentences.

Today we ran into a scenario where we needed to make some text that was defined in a dictionary item a bit more dynamic. Instead of completely replacing the dictionary item with text directly in the template, we decided to look into replacing values in the dictionary item. This would allow editors to still control the majority of the text displayed.

An easy fix would be to simply perform some kind of replacement on the string returned by the specific dictionary item in whatever template you have. That is, however, not very scalable. Therefore I looked into further improving the UmbracoHelper's GetDictionaryValue method with two extension methods:

public static string GetDictionaryValueWithReplacement(this UmbracoHelper umbraco, string key, string pattern, string replacement)
{
    return GetDictionaryValueWithReplacement(umbraco, key, string.Empty, pattern, replacement);
}

public static string GetDictionaryValueWithReplacement(this UmbracoHelper umbraco, string key, string altText, string pattern, string replacement)
{
    return Regex.Replace(umbraco.GetDictionaryValue(key, altText), pattern, replacement);
}
Enter fullscreen mode Exit fullscreen mode

This gives us the possibility to easily reuse the functionality anywhere on the website.

Now, given a dictionary item with the key Some.Dictionary.Item and text This message is super personal for you, %name%. Hope you like it., you can use the extension method above in, for example, a template like so:

@Umbraco.GetDictionaryValueWithReplacement("Some.Dictionary.Item", "%name%", Members.GetCurrentMember().Name)
Enter fullscreen mode Exit fullscreen mode

Which will display the following (in my browser, at least):

This message is super personal for you, Morten Hartvig. Hope you like it.
Enter fullscreen mode Exit fullscreen mode

One could of course make additional methods in order to work with more than one placeholder.. you know, something like:

public static string GetDictionaryValueWithReplacement(this UmbracoHelper umbraco, string key, IDictionary<string, string> replacements)
{
    var value = umbraco.GetDictionaryValue(key);

    foreach (var replacement in replacements)
    {
        value = Regex.Replace(value, replacement.Key, replacement.Value);
    }

    return value;
}
Enter fullscreen mode Exit fullscreen mode

... but that is beyond the scope of what we need so I'll let you play around with that.

Top comments (0)