diff options
Diffstat (limited to 'src/marlin.web/TagHelpers/ActiveLinkTagHelper.cs')
| -rw-r--r-- | src/marlin.web/TagHelpers/ActiveLinkTagHelper.cs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/marlin.web/TagHelpers/ActiveLinkTagHelper.cs b/src/marlin.web/TagHelpers/ActiveLinkTagHelper.cs new file mode 100644 index 0000000..759b701 --- /dev/null +++ b/src/marlin.web/TagHelpers/ActiveLinkTagHelper.cs @@ -0,0 +1,44 @@ +namespace marlin.web.TagHelpers; + +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Razor.TagHelpers; + +[HtmlTargetElement("a", Attributes = "active-when")] +public class ActiveLinkTagHelper : TagHelper +{ + [HtmlAttributeName("asp-controller")] + public string Controller { get; set; } + + [HtmlAttributeName("asp-action")] + public string Action { get; set; } + + [HtmlAttributeName("active-when")] + public ActiveLinkWhen ActiveWhen { get; set; } + + [ViewContext] + [HtmlAttributeNotBound] + public ViewContext ViewContext { get; set; } + + public override void Process(TagHelperContext context, TagHelperOutput output) + { + var currentController = ViewContext.RouteData.Values["controller"]?.ToString(); + var currentAction = ViewContext.RouteData.Values["action"]?.ToString(); + + if (!string.Equals(currentController, Controller, StringComparison.OrdinalIgnoreCase)) + return; + + if (!string.Equals(currentAction, Action, StringComparison.OrdinalIgnoreCase) + && this.ActiveWhen == ActiveLinkWhen.ControllerAndAction) + return; + + var existingClasses = output.Attributes["class"]?.Value?.ToString() ?? ""; + output.Attributes.SetAttribute("class", $"{existingClasses} active".Trim()); + } +} + +public enum ActiveLinkWhen +{ + Controller, + ControllerAndAction +}
\ No newline at end of file |
