Skip to content

An Eleventy shortcode for joining truthy, non-duplicate argument values into a space-delimited string

Notifications You must be signed in to change notification settings

ashur/eleventy-plugin-classnames

Repository files navigation

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>

About

An Eleventy shortcode for joining truthy, non-duplicate argument values into a space-delimited string

Resources

Stars

Watchers

Forks

Packages

No packages published