Integrating some localizer support for encoding and pluralization

Formatter internally encodes information passed as object[] args as appropriate
Resulting LocalizedString marked as html-encoded to prevent double-encoding
Extension method for <%:T.Plural("1 thing", "{0} things", n, ...)%>

--HG--
branch : dev
This commit is contained in:
Louis DeJardin
2010-06-09 15:21:50 -07:00
parent 75449c1abe
commit a190d9bc64
3 changed files with 39 additions and 6 deletions

View File

@@ -1,7 +1,8 @@
using System;
using System.Web;
namespace Orchard.Localization {
public class LocalizedString : MarshalByRefObject {
public class LocalizedString : MarshalByRefObject, IHtmlString {
private readonly string _localized;
public LocalizedString(string localized) {
@@ -20,6 +21,10 @@ namespace Orchard.Localization {
return _localized;
}
string IHtmlString.ToHtmlString() {
return _localized;
}
public override int GetHashCode() {
var hashCode = 0;
if (_localized != null)
@@ -31,8 +36,9 @@ namespace Orchard.Localization {
if (obj == null || obj.GetType() != GetType())
return false;
var that = (LocalizedString) obj;
var that = (LocalizedString)obj;
return string.Equals(_localized, that._localized);
}
}
}

View File

@@ -1,3 +1,11 @@
using System.Linq;
namespace Orchard.Localization {
public delegate LocalizedString Localizer(string text, params object[] args);
}
public static class LocalizerExtensions {
public static LocalizedString Plural(this Localizer T, string textSingular, string textPlural, int count, params object[] args) {
return T(count == 1 ? textSingular : textPlural, new object[] { count }.Concat(args).ToArray());
}
}
}

View File

@@ -1,3 +1,6 @@
using System;
using System.Globalization;
using System.Linq;
using System.Web;
using Orchard.Localization.Services;
using Orchard.Logging;
@@ -23,9 +26,25 @@ namespace Orchard.Localization {
string currentCulture = _cultureManager.GetCurrentCulture(HttpContext.Current);
var localizedFormat = _resourceManager.GetLocalizedString(_scope, textHint, currentCulture);
return args.Length < 1
? new LocalizedString(localizedFormat)
: new LocalizedString(string.Format(localizedFormat, args));
return args.Length == 0
? new LocalizedString(localizedFormat)
: string.Format(GetFormatProvider(currentCulture), localizedFormat, args.Select(Encode).ToArray());
}
private static IFormatProvider GetFormatProvider(string currentCulture) {
try {
return CultureInfo.GetCultureInfoByIetfLanguageTag(currentCulture);
}
catch {
return null;
}
}
static object Encode(object arg) {
if (arg is IFormattable || arg is IHtmlString) {
return arg;
}
return HttpUtility.HtmlEncode(arg);
}
}
}