tl;dr - Is there a function (or a series of functions/workarounds) that will make a given string into a “safe” CSS class name?
Background: I have some data tables with headings, and I’d like to be able to set the CSS class on the heading cells based on the content of the cell. For instance, if the heading is “Age” the class might be heading--age
. The data tables are handled with layout partials, so I have control over the display of the data, but I don’t have control over the data itself.
Right now I’m just using class="heading--{{ replace . " " "_" | lower }}
which takes care of the most common issue of spaces.
But ideally I’d like to also filter it to alphanumeric characters plus underscores and hyphens (in particular to filter out .
and CSS combinators >
, +
, ~
). Technically CSS classes can’t start with digits either, but since I’m prefixing it that doesn’t matter for me.
So I’m just curious, rather than writing a bunch of string replacements, if there’s a function like plainify
or htmlEscape
but for CSS.
Thanks!