A Twig.js extension that allows you to work more easily with html attributes inside Twig templates. The API mimics the Attribute objects in Drupal.
npm install --save @whitespace/twig-extension-attribute-helpers
Import the extension and pass it your Twig object:
import Twig from 'twig';
import extendWithAttributeHelpers from '@whitespace/twig-extension-attribute-helpers';
// Adds the `attributes` function
extendWithAttributeHelpers(Twig);
let data = `<a{{ attributes({
href: '#',
class: ['btn', 'btn-primary']
}) }}>`;
let output = Twig.twig({ data }).render();
// output === `<a href="#" class="btn btn-primary">`
});
Creates and Attribute object containing the passed attributes and values. attrs
should be an object. When rendered it is serialized as HTML attributes. Example:
<a{{ attributes({
href: '#',
class: ['btn', 'btn-primary']
}) }}>
Output:
<a href="#" class="btn btn-primary">
Sets an attribute on an already created Attribute object:
{% set linkAttributes = attributes({
href: '#'
}) %}
<a{{ linkAttributes.setAttribute('target', '_blank') }}>
Output:
<a href="#" target="_blank">
Unsets a previously set attribute
{% set linkAttributes = attributes({
href: '#',
target: '_blank'
}) %}
<a{{ linkAttributes.removeAttribute('target') }}>
Output:
<a href="#">
Adds one or more classes to the class
attribute.
{% set linkAttributes = attributes({
href: '#'
}) %}
<a{{ linkAttributes.addClass('btn', 'btn-primary') }}>
Output:
<a href="#" class="btn btn-primary">
Removes one or more classes from the class
attribute.
{% set linkAttributes = attributes({
href: '#',
class: ['btn', 'btn-primary']
}) %}
<a{{ linkAttributes.removeClass('btn-primary') }}>
Output:
<a href="#" class="btn">
setAttributes(attrs)
getAttribute()
getAttributes()
hasAttribute(attr)
getClass()
hasClass(className)