2011-07-26 108 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的数量级上。