Skip to content

add example: transform custom element / xml to html #1

Description

@milahu
function customElementTransformer(nameCustom, options = {}) {
  const defaultOptions = {
    name: 'div',
    class: nameCustom,
  };
  options = Object.assign(defaultOptions, options);
  const domTransformer = {
    selector: nameCustom,
    transform: ({ elements, document }) => {
      for (let e = 0; e < elements.length; e++) {
        const element = elements[e];
        const elementNew = document.createElement(options.name);
        for (let a = 0; a < element.attributes.length; a++) {
           const attr = element.attributes[a];
           elementNew.setAttribute(attr.name, attr.value); // copy attribute
        }
        elementNew.innerHTML = element.innerHTML; // copy content
        if (options.class) elementNew.classList.add(options.class);
        //element.parentNode.replaceChild(elementNew, element);
        element.replaceWith(elementNew);
      }
    },
  };
  return domTransformer;
}

eleventyConfig.addPlugin(transformDomPlugin, [
  customElementTransformer('page'),
  customElementTransformer('nw', { name: 'span', class: 'nowrap-element' }),
]);

sample input

<page>
  hello world, here are <nw>four non wrapping words</nw>
</page>

sample output

<div class="page">
  hello world, here are <span class="nowrap-element">four non wrapping words</span>
</div>

benefits:

  • the class is also visible in the closing tag
  • shorter open-tags

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions