Merge pull request #824 from hishamco/localizable-component

Localizable component
This commit is contained in:
Shaun Walker 2020-10-20 07:52:11 -04:00 committed by GitHub
commit e61cd3d366
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 22 deletions

View File

@ -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 = "<label";
if (!string.IsNullOrEmpty(For))
{
@ -45,23 +43,10 @@ else
_openLabel += ">";
if (!string.IsNullOrEmpty(ResourceKey))
if (IsLocalizable)
{
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())
{
var localizer = (IStringLocalizer)scope.ServiceProvider.GetService(localizerType);
ChildContent = @<text>@localizer[$"{ResourceKey}.Text"]</text>;
HelpText = localizer[$"{ResourceKey}.{nameof(HelpText)}"];
}
}
ChildContent =@<text>@Localize("Text")</text>;
HelpText = Localize(nameof(HelpText));
}
}
}

View File

@ -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;
}
}
}
}