Skip to content

Commit

Permalink
feat: Filter BEM function classes to conform to CSS spec: https://www…
Browse files Browse the repository at this point in the history
  • Loading branch information
codechefmarc committed Sep 29, 2023
1 parent 2e4c58f commit 0c64934
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions packages/bem-twig-extension/lib/bem-twig-extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ module.exports = bemTwigExtension;
function bemTwigExtension(Twig) {
Twig.extendFunction("bem", function(base_class, modifiers = [], blockname = '', extra = [], attributes = '') {
let classes = [];


// Helper function to sanitize and validate class names
function sanitizeClassName(className) {
// Strips out initial numbers. Replace non-matches with spaces, does strip non-english characters
const sanitized = className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g);
return sanitized ? sanitized.join(' ') : '';
}

// If using a blockname to override default class.
if (blockname.length) {
// Set blockname class.
classes.push(blockname + '__' + base_class);

// Set blockname--modifier classes for each modifier.
if (modifiers.length && Array.isArray(modifiers)) {
modifiers.forEach(function(modifier) {
Expand All @@ -29,14 +36,19 @@ function bemTwigExtension(Twig) {
});
}
}

// If extra non-BEM classes are added.
if (extra.length && Array.isArray(extra)) {
extra.forEach(function(extra_class) {
classes.push(extra_class);
});
}


// Sanitize class names in the classes array
classes = classes.map(function(className) {
return sanitizeClassName(className);
});

attributes = 'class="' + classes.join(' ') + '"';
return attributes;
});
Expand Down

0 comments on commit 0c64934

Please sign in to comment.