@aaashur/eleventy-plugin-classnames

0.2.0 • Public • Published

eleventy-plugin-classnames

An Eleventy plugin — available as a filter and a shortcode — for joining truthy, deduplicated values into a space-delimited string, suitable for use in an HTML element's class attribute:

classnames(
  "block",
  "block__element",
  false && "block__element--modifier",
  "block",
)
// returns "block block__element"

Inspired by the classnames package by JedWatson

Setup

Run the following command at the root of your Eleventy project

npm install @aaashur/eleventy-plugin-classnames

then include it in your .eleventy.js config file:

const classnames = require("@aaashur/eleventy-plugin-classnames");

module.exports = (eleventyConfig) => {
    eleventyConfig.addPlugin(classnames);
};

Usage

classnames is exposed both as a filter and as a shortcode everywhere Eleventy supports them.

Filter

Added in v0.2.0

You might use the filter in a WebC template like this:

---
color: turquoise
primary: false
sectionTitle: Section Title
---
<h2 :class="classnames(
        'block__element',
        primary && 'block__element--primary',
        color && 'block__element--' + color,
    )"
    @text="sectionTitle"
></h2>

which would return:

<h2 class="block__element block__element--turquoise">
    Section Title
</h2>

Shortcode

You might use the shortcode in a Nunjucks template like this:

{%- set color = "turquoise" -%}
{%- set primary = false -%}
{%- set sectionTitle = "Section Title" -%}

<h2 class="{% classnames
    "block__element",
    "block__element--primary" if primary,
    "block__element--" + color if color
%}">
    {{ sectionTitle }}
</h2>

which would return:

<h2 class="block__element block__element--turquoise">
    Section Title
</h2>

Package Sidebar

Install

npm i @aaashur/eleventy-plugin-classnames

Weekly Downloads

3

Version

0.2.0

License

ISC

Unpacked Size

6.17 kB

Total Files

8

Last publish

Collaborators

  • aaashur