Skip to content

Instantly share code, notes, and snippets.

@hbulens
Last active December 9, 2018 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hbulens/5976f6ee3632d56939e59c5151bd243c to your computer and use it in GitHub Desktop.
Save hbulens/5976f6ee3632d56939e59c5151bd243c to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Localization;
using System.Linq;
using System.Reflection;
namespace InjectJavascriptToWebApp
{
internal class ResourceGroup
{
public string Name { get; set; }
public IEnumerable<LocalizedString> Entries { get; set; }
}
[HtmlTargetElement("resources")]
public class ResourcesTagHelper : TagHelper
{
private readonly IStringLocalizerFactory _stringLocalizerFactory;
public ResourcesTagHelper(IStringLocalizerFactory stringLocalizerFactory)
{
_stringLocalizerFactory = stringLocalizerFactory;
}
[HtmlAttributeName("names")]
public string[] Resources { get; set; }
/// <summary>
/// Execute script only once document is loaded.
/// </summary>
public bool OnContentLoaded { get; set; } = false;
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (OnContentLoaded)
await base.ProcessAsync(context, output);
else
{
IEnumerable<ResourceGroup> groupedResources = Resources.Select(x =>
{
IStringLocalizer localizer = _stringLocalizerFactory.Create(x, Assembly.GetEntryAssembly().FullName);
return new ResourceGroup { Name = x, Entries = localizer.GetAllStrings(true).ToList() };
});
StringBuilder sb = new StringBuilder();
sb.Append(groupedResources.ToJavascript());
TagHelperContent content = await output.GetChildContentAsync();
sb.Append(content.GetContent());
output.TagName = "script";
output.Content.AppendHtml(sb.ToString());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment