@ryanmorr/pet

1.0.3 • Public • Published

pet

Version Badge License Build Status

Pseudo-element templating

Install

Download the CJS, ESM, UMD versions or install via NPM:

npm install @ryanmorr/pet

Usage

Pseudo-element templating (pet for short) expands on the capabilities of pseudo-elements by adding support for HTML and data attribute interpolation within the CSS content property.

The beauty of pet is that it's a zero API library, meaning there are no functions to import, just the library itself:

import from '@ryanmorr/pet';

Then add the following to your CSS to ensure the pseudo-element templates are not displayed as plain text:

[pet]::before {
    display: none !important;
}

To begin, indicate an element as a pet element by adding the "pet" attribute. Then define its template within the content property of the ::before pseudo-element:

<div class="component" pet></div>
.component::before {
    content: '<span>Hello World</span>';
}

This will generate the following HTML:

<div class="component" pet>
    <span>Hello World</span>
</div>

Interpolation is achieved through data attributes set on the pet element and mustache-style double curly braces serving as delimiters for tokens within the template. The token found between the delimiters reference the data attribute using the same name conversion as the DOM element dataset property in JavaScript. For example, an attribute of data-foo-bar-baz-qux would be referenced as fooBarBazQux within a template:

<div class="component" data-first-name="John" data-last-name="Doe" pet></div>
.component::before {
    content: '<span>Hello world, my name is {{firstName}} {{lastName}}</span>';
}

This will generate the following HTML:

<div class="component" data-first-name="John" data-last-name="Doe" pet></div>
    <span>Hello world, my name is John Doe</span>
</div>

Programmatically changing a data attribute will automatically patch the changes in the DOM. When a template is updated, a custom "render" event is dispatched on the pet element:

document.querySelector('.component').addEventListener('render', (e) => {
    // React to changes
});

License

This project is dedicated to the public domain as described by the Unlicense.

/@ryanmorr/pet/

    Package Sidebar

    Install

    npm i @ryanmorr/pet

    Weekly Downloads

    4

    Version

    1.0.3

    License

    Unlicense

    Unpacked Size

    11 kB

    Total Files

    6

    Last publish

    Collaborators

    • ryanmorr