diff --git a/Oqtane.Client/Modules/Controls/Label.razor b/Oqtane.Client/Modules/Controls/Label.razor index 0d32a14b..3869d8b4 100644 --- a/Oqtane.Client/Modules/Controls/Label.razor +++ b/Oqtane.Client/Modules/Controls/Label.razor @@ -1,6 +1,5 @@ -@namespace Oqtane.Modules.Controls -@inherits ModuleControlBase -@using Microsoft.Extensions.Localization +@namespace Oqtane.Modules.Controls +@inherits LocalizableComponent @if (!string.IsNullOrEmpty(HelpText)) { @@ -27,11 +26,10 @@ else [Parameter] public string HelpText { get; set; } // optional - tooltip for this label - [Parameter] - public string ResourceKey { get; set; } - protected override void OnParametersSet() { + base.OnParametersSet(); + _openLabel = "@localizer[$"{ResourceKey}.Text"]; - HelpText = localizer[$"{ResourceKey}.{nameof(HelpText)}"]; - } - } + ChildContent =@@Localize("Text"); + HelpText = Localize(nameof(HelpText)); } } } diff --git a/Oqtane.Client/Modules/Controls/LocalizableComponent.cs b/Oqtane.Client/Modules/Controls/LocalizableComponent.cs new file mode 100644 index 00000000..19e1aa46 --- /dev/null +++ b/Oqtane.Client/Modules/Controls/LocalizableComponent.cs @@ -0,0 +1,54 @@ +using System; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Localization; +using Oqtane.Shared; + +namespace Oqtane.Modules.Controls +{ + public class LocalizableComponent : ModuleControlBase + { + private IStringLocalizer _localizer; + + [Parameter] + public string ResourceKey { get; set; } + + protected bool IsLocalizable { get; private set; } + + protected string Localize(string name) + { + if (!IsLocalizable) + { + return null; + } + + var key = $"{ResourceKey}.{name}"; + + return _localizer?[key] ?? key; + } + + protected override void OnParametersSet() + { + if (!String.IsNullOrEmpty(ResourceKey)) + { + if (ModuleState?.ModuleType != null) + { + var moduleType = Type.GetType(ModuleState.ModuleType); + var localizerTypeName = $"Microsoft.Extensions.Localization.IStringLocalizer`1[[{moduleType.AssemblyQualifiedName}]], Microsoft.Extensions.Localization.Abstractions"; + var localizerType = Type.GetType(localizerTypeName); + + // HACK: Use ServiceActivator instead of injecting IHttpContextAccessor, because HttpContext throws NRE in WebAssembly runtime + using (var scope = ServiceActivator.GetScope()) + { + _localizer = (IStringLocalizer)scope.ServiceProvider.GetService(localizerType); + } + } + + IsLocalizable = true; + } + else + { + IsLocalizable = false; + } + } + } +}