drupal-twig-extensions
Version:
JavaScript implementation of Drupal’s Twig extensions
63 lines (58 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.acceptedArguments = void 0;
exports.createAttribute = createAttribute;
exports.options = exports.name = void 0;
var _Attribute = _interopRequireDefault(require("../../Attribute.cjs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @file The create_attribute function
*
* Docs for TwigExtension::createAttribute (Drupal 9.3.x):
*
* ```
* new TwigFunction('create_attribute', [$this, 'createAttribute'])
* ```
*/
const name = 'create_attribute';
exports.name = name;
const options = {};
exports.options = options;
const acceptedArguments = [{
name: 'attributes',
defaultValue: {}
}];
/**
* Creates an Attribute object.
*
* @param {?Object<string, string|string[]>} attributes
* (optional) An associative array of key-value pairs to be converted to
* HTML attributes.
*
* @returns {Attribute}
* An attributes object that has the given attributes.
*/
exports.acceptedArguments = acceptedArguments;
function createAttribute(attributes = {}) {
let attributeObject;
// @TODO: https://github.com/JohnAlbin/drupal-twig-extensions/issues/1
if (attributes instanceof Map || Array.isArray(attributes)) {
attributeObject = new _Attribute.default(attributes);
} else {
attributeObject = new _Attribute.default();
// Loop through all the given attributes, if any.
if (attributes) {
Object.keys(attributes).forEach(key => {
// Ensure class is always an array.
if (key === 'class' && !Array.isArray(attributes[key])) {
attributeObject.setAttribute(key, [attributes[key]]);
} else {
attributeObject.setAttribute(key, attributes[key]);
}
});
}
}
return attributeObject;
}