Inspired by Svelte class shortcuts
class:name="@Model.Value"class:nameClassApplicatorTagHelper provides a shorter way of toggling a class on an element.
<!-- These are equivalent -->
<div class="(@Model.Active ? 'active' : '')">...</div>
<div class:active="@Model.Active">...</div>
<!-- Shorthand, for when name and value match -->
<div class:active>...</div>
<!-- Multiple class toggles can be included -->
<div class:active class:inactive="@(!Model.Active)" class:isAdmin>...</div>In your _ViewImports.cshtml file add:
@addTagHelper *, SingleFileLibrariesTo set a class based on the boolean value of a property on your model
<span class:is-active="@Model.IsActive">Is active</span>To change the attribute prefix from class: to something else just modify the Prefix constant
public const string Prefix = "class:";You can also use the shortcut version if the class name and the property name are the same.
Class names to property names are case insensitive. Characters such as - and _ are removed
from the class name and then compared against the property name.
If the value is not a boolean but non-null the class name will also be applied.
<span class:is-active>Is active</span>
<span class:name>Name</span><span class="is-active">Is active</span>
<span class="name">Name</span>You can chain classnames to the same model value. Chaining classnames using the shortcut method will check each classname against a property of the same name.
<span class:is-active|text-success="@Model.IsActive">Is Active</span><span class="is-active text-success">Is active</span>