在Umbraco v6中,可以使用以下命令获取dictionaryitem:
umbraco.library.GetDictionaryItem("EmailSubject");
Run Code Online (Sandbox Code Playgroud)
这将检索"EmailSubject"的正确值,具体取决于用户访问umbraco网站的文化.
现在我正在编写一个简单的电子邮件类库,我不关心System.Threading.Thread.CurrentThread.CurrentCulture,我不想在获取值之前始终设置CurrentCulture.它有效,但我不喜欢这种方法.我正在写一个简单的邮件库.对于每个邮件收件人,我认为设置这样的文化并不是很有效.
我找到的解决方案(在线搜索,我遗失了来源抱歉)是以下示例:
//2 = the 2nd language installed under Settings > Languages, which is German in my case
var sometext = new umbraco.cms.businesslogic.Dictionary.DictionaryItem("SomeText").Value(2);
Run Code Online (Sandbox Code Playgroud)
我创建了一些帮助方法,使其更容易:
private string GetDictionaryText(string dictionaryItem, string language)
{
//try to retrieve from the cache
string dictionaryText = (string)HttpContext.Current.Cache.Get(dictionaryItem + language);
if (dictionaryText == null)
{
dictionaryText = new umbraco.cms.businesslogic.Dictionary.DictionaryItem(dictionaryItem).Value(GetLanguageId(language));
//add to cache
HttpContext.Current.Cache.Insert(dictionaryItem + language, dictionaryText, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
}
return dictionaryText;
}
private int GetLanguageId(string language)
{
int languageId = 1; //1 = english, 2 = german, 3 = french, 4 = italian
switch (language)
{
case "de":
languageId = 2;
break;
case "fr":
languageId = 3;
break;
case "it":
languageId = 4;
break;
}
return languageId;
}
Run Code Online (Sandbox Code Playgroud)
使用我的帮助程序以德语获取"EmailSubject"的示例:
string emailSubject = GetDictionaryText("EmailSubject", "de");
Run Code Online (Sandbox Code Playgroud)
这有效(用umbraco 6.2.x进行测试)但是你可以注意到,每次你想要这样的文本时,都必须创建一个umbraco.cms.businesslogic.Dictionary.DictionaryItem类的新实例...这不是必要的坏,但我想知道是否有一个静态方法可用于此,也许允许指定语言或文化(作为字符串)而不是语言或文化ID,可以在不同的环境中有所不同...
由于umbraco API非常庞大(有时一些很酷的功能没有记录),我找不到更好的解决方案,我想知道是否有更好的umbraco"本地"方式来实现这一点,没有额外的帮助方法,因为我以上所列.
在您的答案中,请列出您正在使用的umbraco版本.
使用LocalizationService按语言获取字典项.我创建了一个静态方法来执行此操作:
public static string GetDictionaryValue(string key, CultureInfo culture, UmbracoContext context)
{
var dictionaryItem = context.Application.Services.LocalizationService.GetDictionaryItemByKey(key);
if (dictionaryItem != null)
{
var translation = dictionaryItem.Translations.SingleOrDefault(x => x.Language.CultureInfo.Equals(culture));
if (translation != null)
return translation.Value;
}
return key; // if not found, return key
}
Run Code Online (Sandbox Code Playgroud)
小智 1
据我所知,Umbraco 目前没有静态方法来获取特定语言的字典项。我必须像你一样按语言获取字典项目(我使用 Umbraco 版本 7.2.8)。但是,我通过 Umbraco 提供的功能获取语言列表。
我希望Umbraco在未来的版本中添加这个功能。我觉得像你说的那样是有必要的。