Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [HtmlTargetElement(Attributes = "class")]
- public class InlineClassTagHelper : TagHelper
- {
- private readonly IFileProvider _fileProvider;
- public InlineClassTagHelper(IFileProvider fileProvider)
- {
- _fileProvider = fileProvider;
- }
- [HtmlAttributeNotBound, ViewContext]
- public ViewContext ViewContext { get; set; }
- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
- {
- var classNames =
- output
- .Attributes["class"]
- ?.Value.ToString()
- .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
- .Where(className => className.StartsWith("m-"))
- .Select(SoftString.Create)
- .ToImmutableHashSet();
- if (classNames is null)
- {
- return;
- }
- var cssFileName =
- $"wwwroot/css/" +
- $"{ViewContext.RouteData.Values["controller"]}." +
- $"{ViewContext.RouteData.Values["action"]}.css";
- var cssFile = _fileProvider.GetFileInfo(cssFileName);
- var cssString = await ReadFile(cssFile);
- var css = CssParser.Default.Parse(cssString);
- var declarations = css.Where(ruleset => ruleset.Selectors.Any(classNames.Contains)).Select(ruleset => ruleset.Declarations).Join(";");
- output.Attributes.SetAttribute("style", declarations);
- output.Attributes.RemoveAll("class");
- }
- private static async Task<string> ReadFile(IFileInfo file)
- {
- using (var reader = new StreamReader(file.CreateReadStream()))
- {
- return await reader.ReadToEndAsync();
- }
- }
- }
- <h2 class="m-title">@ViewData["Title"]</h2>
- <h2 style="color: blueviolet;">About</h2>
- m-title {
- color: blueviolet;
- }
Add Comment
Please, Sign In to add comment