Created
February 8, 2017 18:08
-
-
Save naepalm/3972cf3e126935511c4792d74d748fa2 to your computer and use it in GitHub Desktop.
Get all dictionary items for a language on a site and spit them out in an API Controller.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()".