This package replicates the functionality of the popular JS package JedWatson/classnames, allowing you to easily build HTML classlists using strings, stringable objects and arrays with conditions, like this:
Classnames::from(
'btn',
['btn-primary'],
['btn-secondary' => false],
['btn-wide' => true],
new StringableObject('btn-lg')
);
// => 'btn btn-primary btn-wide btn-lg'
You can install the package via composer:
composer require pangora/classnames
Classnames accepts multiple arguments through the static from
method and it'll respect the argument order when building the classlist. The from
method won't remove duplicates, but you may use the static dedupeFrom
, which works the same way, while also removing duplicates.
The allowed argument types are:
string
int
(will be converted tostring
)- Any "stringable" object implementing the magic
__toString()
method. - Sequential arrays
- Associative arrays where the key represents the value and the value represent the condition.
Arguments of other types will be ignored, except for multidimensional array which will throw an exception.
Classnames::from('btn btn-primary');
// => 'btn btn-primary'
Classnames::from('btn', 'btn-primary');
// => 'btn btn-primary'
Classnames::from(' lots of ', ' space ');
// => 'lots of space'
Classnames::from('btn', ['btn-primary']);
// => 'btn btn-primary'
Classnames::from([
'btn' => false,
'btn-secondary' => false,
'btn-primary' => true,
]);
// => 'btn btn-primary'
Classnames::from(
'card',
new StringableObject('card-lg')
);
// => 'card card-lg'
You may also deduplicate the classlist using dedupefrom
:
Classnames::dedupeFrom('a btn b btn c');
// => 'a btn b c'
composer test
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email jarand@pangora.no instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.