Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

TagHelperExtensions.cs

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Nop.Web.Framework.Extensions;

namespace Nop.Web.Framework.TagHelpers;

/// 
/// Tag helper extensions
/// 
public static class TagHelperExtensions
{
    #region Methods

    /// 
    /// Get string value from tag helper output
    /// 
    /// An information associated with the current HTML tag
    /// Name of the attribute
    /// Matching name
    public static async Task GetAttributeValueAsync(this TagHelperOutput output, string attributeName)
    {

        if (string.IsNullOrEmpty(attributeName) || !output.Attributes.TryGetAttribute(attributeName, out var attr))
            return null;

        if (attr.Value is string stringValue)
            return stringValue;

        return attr.Value switch
        {
            HtmlString htmlString => htmlString.ToString(),
            IHtmlContent content => await content.RenderHtmlContentAsync(),
            _ => default
        };
    }

    /// 
    /// Get attributes from tag helper output as collection of key/string value pairs
    /// 
    /// A stateful HTML element used to generate an HTML tag
    /// Collection of key/string value pairs
    public static async Task> GetAttributeDictionaryAsync(this TagHelperOutput output)
    {
        ArgumentNullException.ThrowIfNull(output);

        var result = new Dictionary();

        if (!output.Attributes.Any())
            return result;

        foreach (var attrName in output.Attributes.Select(x => x.Name).Distinct())
        {
            result.Add(attrName, await output.GetAttributeValueAsync(attrName));
        }

        return result;
    }

    #endregion
}