2010-11-23 61 views
2

我想构建一个多语言的ASP.NET MVC 2网站。ASP.NET MVC2本地化:如何格式化语言/国家依存文本?

比方说,我有如下的句子:

MyStrings.resx: 
TestString : "This is my test" 

MyStrings.de.resx: 
TestString : "Dies ist mein Test" 

MyStrings.fr.resx: 
TestString : "C'est mon test" 

现在在我的网站我想打的话在其他颜色我/炒面/周一例如,我想分配一个其他的span类。什么是最好的/标准的做法呢?

我该怎么做?

回答

4
  1. 你可以混合使用HTML到您的资源:"This is <span class="x">my</span> test"
  2. 你可以使用string.Format:资源:"This is {0}my{1} test",用途:string.Format(Resources.TestString, "<span class=\"x\">", "</span">)
  3. 您可以使用一些自定义的格式化方案:例如资源:"This is --my-- test",并编写一些接受字符串的扩展方法,并用正确的标记替换所有--

UPDATE
4.您可以使用自定义格式的方法。见下面的代码。

你的资源可能看起来像Hello {firstname}, you still have {amount} {currency} in your bankaccount.你会“消耗”通过以下方式这一资源:

Resources.Bla.Bla.FormatWith(new { Firstname = SomeVariable, AMOUNT = 4, currency = "USD" }); 

正如你可以看到,这是不区分大小写,并且可以在常量和变量混合。我制作了一个自定义翻译的网络应用程序,在这里我检查翻译者是否使用原始英文字符串中存在的所有“变量”。据我所知,这是一项非常重要的检查。
让我补充说,这种方式有点争议,因为它使用反射,但我发现专业人士比权重更重。

public static string FormatWith(this string format, object source) 
    { 
     StringBuilder sbResult = new StringBuilder(format.Length); 
     StringBuilder sbCurrentTerm = new StringBuilder(); 
     char[] formatChars = format.ToCharArray(); 
     bool inTerm = false; 
     object currentPropValue = source; 

     var sourceProps = source.GetType().GetProperties(); 

     for (int i = 0; i < format.Length; i++) 
     { 
      if (formatChars[i] == '{') 
       inTerm = true; 
      else if (formatChars[i] == '}') 
      { 
       PropertyInfo pi = sourceProps.First(sp=>sp.Name.Equals(sbCurrentTerm.ToString(), StringComparison.InvariantCultureIgnoreCase)); 
       sbResult.Append((string)(pi.PropertyType.GetMethod("ToString", new Type[] { }).Invoke(pi.GetValue(currentPropValue, null) ?? string.Empty, null))); 
       sbCurrentTerm.Clear(); 
       inTerm = false; 
       currentPropValue = source; 
      } 
      else if (inTerm) 
      { 
       if (formatChars[i] == '.') 
       { 
        PropertyInfo pi = currentPropValue.GetType().GetProperty(sbCurrentTerm.ToString()); 
        currentPropValue = pi.GetValue(source, null); 
        sbCurrentTerm.Clear(); 
       } 
       else 
        sbCurrentTerm.Append(formatChars[i]); 
      } 
      else 
       sbResult.Append(formatChars[i]); 
     } 
     return sbResult.ToString(); 
    } 
+0

方式1似乎非常好。但是后来我需要照顾自己逃跑的特殊字符:-(像几乎每个人都在解决这个问题的“标准”方式,这三种方式中的一种? – Chris 2010-11-23 16:50:45