Skip to content

Instantly share code, notes, and snippets.

@nadjibus
Created November 2, 2022 21:07
Show Gist options
  • Save nadjibus/f45fc95ca76353bc5bc72ffe275d4b29 to your computer and use it in GitHub Desktop.
Save nadjibus/f45fc95ca76353bc5bc72ffe275d4b29 to your computer and use it in GitHub Desktop.
An ASP.NET Core Tag Helper that makes localization pretty straightforward
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);
}
}
@nadjibus
Copy link
Author

nadjibus commented Nov 3, 2022

Don't forget to add @addTagHelper *, YourWebAppAssembly to _ViewImports.cshtml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment