2011-07-26 106 views
4

本地化ASP.NET應用程序(MVC或webforms,無所謂)時,如何處理資源文件中的HTML字符串?特別是,你如何處理像嵌入式動態鏈接的段落?到目前爲止,我的策略是使用某種形式的href屬性值的佔位符,並在運行時將其替換爲實際的URL,但這看起來似乎很虛幻。ASP.NET本地化

舉個例子,假設我的副本是:

Thank you for registering. Click 
<a href="{prefs_url}">here</a> 
to update your preferences. 
To login and begin using the app, click 
<a href="{login_url}">here</a>. 

使用MVC(剃刀),這可能是一個簡單的:

<p>@Resources.Strings.ThankYouMessage</p> 

現在變成

<p>@Resources.Strings.ThankYouMessage 
    .Replace("{prefs_url}", Url.Action("Preferences", "User")) 
    .Replace("{login_url}", Url.Action("Login", "User"))</p> 

這是不可怕,但我想我只是想知道是否有更好的方法?

+0

在過去的MVC中,我調整了HtmlHelper在這裏找到:http://www.eworldui.net/blog/post/2008/05/ASPNET-MVC---Localization.aspx它工作得很好,並允許我改爲使用常規的字符串格式佔位符。缺點是這比字符串替換更不容忍。 –

回答

1

除了一些語法和性能調整之外,沒有更好的方法。例如,您可能會添加一個緩存層,以便您不針對每個請求執行這些字符串操作。事情是這樣的:

<p>@Resources.LocalizedStrings.ThankYouMessage</p> 

這或許調用一個函數是這樣的:

Localize("ThankYouMessage", Resources.Strings.ThankYouMessage) 

它通過資源+文化做一個哈希表查找:

//use Hashtable instead of Dictionary<> because DictionaryBase is not thread safe. 
private static System.Collections.Hashtable _cache = 
    System.Collections.Hashtable.Synchronized(new Hashtable()); 

public static string Localize(string resourceName, string resourceContent) { 
    string cultureName = System.Threading.Thread.CurrentThread.CurrentCulture.Name; 

    if (string.IsNullOrEmpty(resourceName)) 
     throw new ArgumentException("'resourceName' is null or empty."); 

    string cacheKey = resourceName + "/" + cultureName; 

    object o = _cache[cacheKey]; 

    if (null == o) { //first generation; add it to the cache. 
     _cache[cacheKey] = o = ReplaceTokensWithValues(resourceContent); 
    } 

    return o as string; 
} 

通知調用ReplaceTokensWithValues()。這是一個包含所有「不可怕」的字符串替換fiffery功能:

public static string ReplaceTokensWithValues(string s) { 
    return s.Replace("{prefs_url}", Url.Action("Preferences", "User")) 
     .Replace("{login_url}", Url.Action("Login", "User") 
     .Replace("{any_other_stuff}", "random stuff"); 
} 

通過使用上述高速緩存方法,ReplaceTokensWithValues()只叫一次每個文化,每個資源爲的壽命應用程序 - 每個資源調用一次。差異可能在100比100,000的數量級上。