PHPackages                             timkelty/craftcms-classmate - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. timkelty/craftcms-classmate

ActiveCraft-plugin[Utility &amp; Helpers](/categories/utility)

timkelty/craftcms-classmate
===========================

HTML class helper

1.1.0(5y ago)76.7k[3 issues](https://github.com/timkelty/craftcms-classmate/issues)MITPHP

Since Jan 19Pushed 5y ago1 watchersCompare

[ Source](https://github.com/timkelty/craftcms-classmate)[ Packagist](https://packagist.org/packages/timkelty/craftcms-classmate)[ RSS](/packages/timkelty-craftcms-classmate/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (5)Versions (6)Used By (0)

Classmate for Craft CMS 3
=========================

[](#classmate-for-craft-cms-3)

[![Donate](https://camo.githubusercontent.com/604e3db9c8751116b3f765aad0353ec7ded655bbe8aaacbc38d8c4a6b784b3ed/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f446f6e6174652d50617950616c2d677265656e2e737667)](https://www.paypal.com/donate?hosted_button_id=A5FPKHYV4GRTC)

[![Test Status](https://github.com/timkelty/craftcms-classmate/workflows/Codeception/badge.svg)](https://github.com/timkelty/craftcms-classmate/workflows/Codeception/badge.svg)

Classmate is here to help with HTML class composition and is especially useful when paired with a [utility-first](https://tailwindcss.com/docs/utility-first) css framework, such as [Tailwind CSS](http://tailwindcss.com/).

### Before Classmate:

[](#before-classmate)

`template.twig`

```

  Some reusable heading…
  A link

```

### After Classmate:

[](#after-classmate)

`template.twig`

```

  Some reusable heading…
  A link

```

`classmate.json`

```
{
  "myHeading": "text-lg leading-6 font-medium text-gray-900",
  "defaultLink": "text-orange-600 hover:text-orange-900"
}
```

Why?
----

[](#why)

My opinons about [Extracting component classes with `@apply`](https://tailwindcss.com/docs/extracting-components#extracting-component-classes-with-apply) are pretty well summed up by [this tweet](https://twitter.com/adamwathan/status/1308944904786268161):

[![Flowchart: "Should you extract a component class with @apply"](https://camo.githubusercontent.com/3e6f67d9afaebea4228342f4594f24e1699c4883d16e7a0902350a9de6a28a5d/68747470733a2f2f7062732e7477696d672e636f6d2f6d656469612f4569704e573937577341496c3851443f666f726d61743d6a7067266e616d653d343039367834303936)](https://camo.githubusercontent.com/3e6f67d9afaebea4228342f4594f24e1699c4883d16e7a0902350a9de6a28a5d/68747470733a2f2f7062732e7477696d672e636f6d2f6d656469612f4569704e573937577341496c3851443f666f726d61743d6a7067266e616d653d343039367834303936)

In short, I tend to avoid `@apply` when possible.

*Classmate was created specifically for single element components (e.g. button, link, heading), where extracting to a template partial may be cumbersome and you still want to avoid `@apply`.*

**How is this better than @apply? Aren't we just moving problem elsewhere?**

Yes and no. It is true that the practice of extracting components with `@apply` is similar to defining classes in classmate JSON file. However, Classmate abstracts the definition on the backend (PHP), while `@apply` abstracts it as part of the front-end build. Advantages to this are:

- No additional CSS bloat from component classes
- No added compile time from `@apply`
- Your resulting HTML remains all-utility. Onboarding a new developer to project, especially if they're already familiar with Tailwind or whatever framework, is much easier if they don't have to decipher a set of component classes.
- Errors are more easily caught.
    - With an extracted component, misuse can happen easily and go unnoticed, e.g. a typo in your class attribute. With Classmate, when a class definition is missing, it is readily apparent to the developer.
- Config can be shared with frontend JS.

Configuration
-------------

[](#configuration)

Copy `./src/config.php` to `/config/classmate.php`.

### `filePath`

[](#filepath)

The location of your Classmate file. Aliases and environment variables are supported. Defaults to `@config/classmate.json`, but I suggest you put it alongside your pre-compiled frontend assets, e.g. `./src/css/classmate.json`

If using Tailwind or PurgeCSS directly, you will also want to include this path. E.g.

`tailwind.config.js`

```
module.exports = {
  purge: {
    content: [
      "./src/**/*.css",
      "./src/**/*.js",
      "./templates/**/*.*",
      "./config/tailwind.json",
    ],
    options: {
      safelist: [],
    },
  },
};
```

Classmate File
--------------

[](#classmate-file)

Your Classmate file is a JSON file with a single object. The values can be space separated strings or arrays, or a combination of both.

```
{
  "heading1": "text-2xl font-bold",
  "heading2": ["text-lg", "font-bold"],
  "buttonBase": [
    "text-center inline-flex items-center justify-center font-bold",
    "rounded-full"
  ],
  "buttonWhite": "bg-white text-gray-900",
  "buttonLg": "leading-none text-xl py-4 px-8",
  "buttonSm": "leading-none text-sm py-2 px-4",
  "centerX": "left-1/2 transform -translate-x-1/2",
  "centerY": "top-1/2 transform -translate-y-1/2"
}
```

Since this is just a JSON file, it is easily consumable by Javascript, too!

```
import classmate from "../../config/classmate.json";
document.querySelector("body").class = classmate.body;
```

Usage
-----

[](#usage)

### `tag` function

[](#tag-function)

```
{{ tag('a', classmate.get('defaultLink').asAttributes({
  text: 'A link'
  href: '#'
})) }}
```

### `tag` tag

[](#tag-tag)

*Craft 3.6+ only*

```
{% tag('a', classmate.get('defaultLink').asAttributes({href: '#' })) %}
  A link
{% endtag %}
```

### `attr` function

[](#attr-function)

```
A link
```

### `attr` filter

[](#attr-filter)

```
{% set tag = '' %}
{{ tag|attr({
    class: classmate.get('defaultLink').asClasses()
}) }}
```

### Class string

[](#class-string)

```
A link
```

API
---

[](#api)

`classmate` is a chainable API, available as a global in your Twig templates.

### `get(string ...$keys): Classmate`

[](#getstring-keys-classmate)

Retrive classes of given `$keys` from your classmate file. Multiple keys will be merged right to left.

```
{{ classmate.get('buttonBase', 'buttonLarge', 'buttonBlue') }}
```

### `asClasses(): array`

[](#asclasses-array)

Retrive an array of classes. Duplicates and empty values are removed.

```

```

### `add(string ...$classes): Classmate`

[](#addstring-classes-classmate)

Add classes to the current `ClassList`.

```
{{ classmate.get('foo').add('mb-4') }}
```

### `remove(string ...$classes): Classmate`

[](#removestring-classes-classmate)

Remove classes to the current `ClassList`.

```
{{ classmate.get('foo').remove('mb-4') }}
```

### `matching(string $pattern): Classmate`

[](#matchingstring-pattern-classmate)

Filter the current `ClassList`, keeping those that match `$pattern`.

```
{{ classmate.get('foo').matching('/^text-/') }}
```

### `notMatching(string $pattern): Classmate`

[](#notmatchingstring-pattern-classmate)

Filter the current `ClassList`, removing those that match `$pattern`.

```
{{ classmate.get('foo').notMatching('/^mb-/') }}
```

### `replace(string $search, string $replace, bool $partial = false): Classmate`

[](#replacestring-search-string-replace-bool-partial--false-classmate)

Replace `$search` with `$replace`. Set `$partial` to `true` to match partial strings, otherwise only complete matches will be replaced.

```
{{ classmate.get('foo').replace('text-red-500', 'text-red-100') }}
{{ classmate.get('bar').replace('md:', 'lg:', true) }}
```

### `prepend(string $string): Classmate`

[](#prependstring-string-classmate)

Prepend `$string` to each item in the `ClassList`.

```
{{ classmate.get('foo').prepend('md:') }}
```

### `append(string $string): Classmate`

[](#appendstring-string-classmate)

Append `$string` to each item in the `ClassList`.

Cache
-----

[](#cache)

Retrival of the JSON file is cached, and invalidated by modifications to the file, so you really shouldn't have to worry much about invalidation. However, you can selectively clear the cache via the CP or with the CLI command:

```
./craft clear-caches/classmate-cache
```

Requirements
------------

[](#requirements)

- Craft CMS 3.0+
- PHP 7.4+

Installation
------------

[](#installation)

```
composer require timkelty/craftcms-classmate
```

Roadmap
-------

[](#roadmap)

### How do I use Classmate classes in css?

[](#how-do-i-use-classmate-classes-in-css)

You can't! …yet. @markhuot alluded to this here:

A Tailwind/Postcss plugin might allow something like:

E.g. you write

```
.prose a {
  @classmate foo, bar;
}
```

…to grab classes the same what that `classmate.get('foo', 'bar')` would.

### Arrow Functions

[](#arrow-functions)

I'd love to allow the use of arrow functions, but Twig currently doesn't allow it. For example, instead of our `matches` and `prepend` methods, I'd rather have:

```
classmate.get('foo').filter(c => c starts with 'f')
classmate.get('foo').filter(c => c matches '/^f/')
classmate.get('foo').map(c => "md:#{c}")
```

While this works for Twig's `map`, `filter`, and `reduce` filters, it doesn't work here. See [twigphp/Twig#3402](https://github.com/twigphp/Twig/issues/3402)

### CP settings

[](#cp-settings)

I don't really have a desire for this, but happy to accept a PR if someone wants to add this.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance11

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

5

Last Release

1940d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f17a828989c32b4dc355214677bca83beeb894450f4ddb3c2b7fa4897712457c?d=identicon)[timkelty](/maintainers/timkelty)

---

Tags

cmstailwindCraftcraftcmscraft-pluginclassmate

###  Code Quality

TestsCodeception

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/timkelty-craftcms-classmate/health.svg)

```
[![Health](https://phpackages.com/badges/timkelty-craftcms-classmate/health.svg)](https://phpackages.com/packages/timkelty-craftcms-classmate)
```

###  Alternatives

[verbb/navigation

Create navigation menus for your site.

90683.7k17](/packages/verbb-navigation)[verbb/formie

The most user-friendly forms plugin for Craft.

101372.9k40](/packages/verbb-formie)[verbb/comments

Add comments to your site.

13753.1k](/packages/verbb-comments)[verbb/tablemaker

Create customizable and user-defined table fields.

40168.8k1](/packages/verbb-tablemaker)[supercool/tablemaker

Create customizable and user-defined table fields.

40141.7k](/packages/supercool-tablemaker)[pennebaker/craft-architect

CraftCMS plugin to generate content models from JSON/YAML data.

72148.5k5](/packages/pennebaker-craft-architect)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
