ASP.NET MVC2本地化:如何格式化语言/国家/地区依赖文本?

时间:2010-11-23 14:01:12

标签: asp.net asp.net-mvc asp.net-mvc-2 resources localization

我想构建一个多语言ASP.NET MVC 2网站。

假设我有以下句子:

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

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

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

现在,在我的网站上,我想用另一种颜色制作单词my / mein / mon。例如,我想设计另一个span类。这样做的最佳/标准做法是什么?

我该怎么做?

1 个答案:

答案 0 :(得分: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",并编写一些接受字符串的扩展方法,并用正确的标记替换所有--
  4. <强>更新
     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();
        }