Created
November 2, 2022 21:07
-
-
Save nadjibus/f45fc95ca76353bc5bc72ffe275d4b29 to your computer and use it in GitHub Desktop.
An ASP.NET Core Tag Helper that makes localization pretty straightforward
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Razor.TagHelpers; | |
[HtmlTargetElement(LocalizeTagName)] // This is for <localize>Content here</localize> syntax | |
[HtmlTargetElement(Attributes = LocalizeTagName)] // This is for <p localize>Content here</p> syntax, which I personally prefer | |
public class LocalizeTagHelper : TagHelper | |
{ | |
private const string LocalizeTagName = "localize"; | |
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) | |
{ | |
var childContent = await output.GetChildContentAsync(); | |
var content = childContent.GetContent(); | |
// Removes the "localize" tag | |
if (output.TagName == LocalizeTagName) | |
output.TagName = null; | |
// Empty tag content... | |
if (string.IsNullOrEmpty(content)) | |
{ | |
await base.ProcessAsync(context, output); | |
return; | |
} | |
// Get the localization (here using .NET ResourceManager), or the original content if not found | |
var localization = AppResources.ResourceManager.GetString(content) ?? content; | |
output!.Content!.SetHtmlContent(localization); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to add
@addTagHelper *, YourWebAppAssembly
to _ViewImports.cshtml