A utility to construct HTML class name strings in PHP.
Install the package via Composer
composer require jerrylopez/classnames
Adding multiple sets of class name strings into the array will be concatenated in the output.
<?php
use function Jerrylopez\Classnames\{classnames}
?>
<div class="<?= classnames([
'bg-blue md:px-6 md:py-6',
'text-xl semibold',
]) ?>">
...
</div>
<!-- Output -->
<div class="bg-blue md:px-6 md:py-6 text-xl semibold">
...
</div>
Adding an array with the class names as the key and a true returning condition as the value will include the class names in the output.
<?php
use function Jerrylopez\Classnames\{classnames}
?>
<div class="<?= classnames([
'bg-blue md:px-6 md:py-6',
'text-xl semibold',
['bg-green' => $this->someMethodThatReturnsTrue()]
]) ?>">
...
</div>
<!-- Output -->
<div class="bg-blue md:px-6 md:py-6 text-xl semibold bg-green">
...
</div>
Adding an array with the class names as the key and a false returning condition as the value will exclude the class names from the output.
<?php
use function Jerrylopez\Classnames\{classnames}
?>
<div class="<?= classnames([
'bg-blue md:px-6 md:py-6',
'text-xl semibold',
['bg-green' => $this->someMethodThatReturnsFalse()]
]) ?>">
...
</div>
<!-- Output -->
<div class="bg-blue md:px-6 md:py-6 text-xl semibold">
...
</div>
This utility also comes with an alias cn
that can be used as a shorthand for the classnames
function.
<?php
use function Jerrylopez\Classnames\{cn}
?>
<div class="<?= cn([
'bg-blue md:px-6 md:py-6',
'text-xl semibold'
]) ?>">
...
</div>
<!-- Output -->
<div class="bg-blue md:px-6 md:py-6 text-xl semibold">
...
</div>
This package was inspired by the clsx package in JS community.