Posted Monday, 12 October 2020 by Jeremy Cook

Attributes Toggle Tag Helper

Example CSHTML:

@var somethingBoolean = true;
<div sk-bool-data-template="@somethingBoolean" sk-bool-other="false">...</div>

Resulting HTML:

<div data-template>...</div>

The Code:

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;

namespace SiteKit.AspNetCore.TagHelpers
{
    [HtmlTargetElement(Attributes = BoolPrefix + "*")]
    public class SkBoolAttributeTagHelper : TagHelper
    {
        private const string BoolPrefix = "sk-bool-";

        private IDictionary<string, bool>? _boolValues;

        [HtmlAttributeName(DictionaryAttributePrefix = BoolPrefix)]
        public IDictionary<string, bool> BoolValues
        {
            get
            {
                if (_boolValues == null)
                {
                    _boolValues = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
                }

                return _boolValues;
            }
            set
            {
                _boolValues = value;
            }
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (_boolValues != null)
            {
                foreach (var item in _boolValues)
                {
                    if (item.Value)
                    {
                        output.Attributes.Add(item.Key, null);
                    }
                }
            }
        }
    }
}