Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get all dictionary items for a language on a site and spit them out in an API Controller.
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Web;
using Umbraco.Web.WebApi;
namespace Olympic.Web.Controllers.Api
{
public class DictionaryController : UmbracoApiController
{
private readonly UmbracoHelper _umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
public IEnumerable<DictionaryItem> GetDictionaryItems(string culture = "en-US")
{
//For now, we're only going to get the English items
var dictionary = new List<DictionaryItem>();
var root = ApplicationContext.Services.LocalizationService.GetRootDictionaryItems();
if (!root.Any())
{
return Enumerable.Empty<DictionaryItem>();
}
foreach (var item in root)
{
dictionary.Add(new DictionaryItem
{
Key = item.ItemKey,
Value = item.Translations.Where(x => x.Language.CultureName == culture).Select(x => x.Value).FirstOrDefault()
});
dictionary.AddRange(LoopThroughDictionaryChildren(item.Key, culture));
}
return dictionary;
}
private IEnumerable<DictionaryItem> LoopThroughDictionaryChildren(Guid key, string culture)
{
var dictionary = new List<DictionaryItem>();
var items = Services.LocalizationService.GetDictionaryItemChildren(key);
if (!items.Any())
{
return Enumerable.Empty<DictionaryItem>();
}
foreach (var subItem in items)
{
dictionary.Add(new DictionaryItem
{
Key = subItem.ItemKey,
Value = subItem.Translations.Where(x => x.Language.CultureName == culture).Select(x => x.Value).FirstOrDefault()
});
dictionary.AddRange(LoopThroughDictionaryChildren(subItem.Key, culture));
}
return dictionary;
}
}
public class DictionaryItem
{
public string Key { get; set; }
public string Value { get; set; }
}
}
@nickolajEcreo
Copy link

Thank you for sharing!
There is a small error however. When you compare til string "culture" with "Language.CultureName". The correct comparison is using "Language.CultureInfo.ToString()".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment