Closed dextermb closed 2 months ago
As a follow up to my original comment I've created my own attribute bag helper, which allows for boolean conditions one level deep:
ComponentAttributeBag::macro("cn", function (
...$args
): ComponentAttributeBag {
/** @var ComponentAttributeBag $this */
$attr = $this->get("class", "");
$attr .= collect($args)->reduce(function (string $carry, mixed $arg) {
if (!$arg) {
return $carry;
}
if (is_array($arg)) {
$reduced = collect($arg)
->filter(fn(mixed $boolish) => !!$boolish)
->map(fn(mixed $a, mixed $b) => is_numeric($b) ? $a : $b)
->join(" ");
return $carry . " " . $reduced;
}
return $carry . " " . $arg;
}, "");
$this->offsetSet("class", twMerge($attr));
return $this;
});
As a follow up to my original comment I've created my own attribute bag helper, which allows for boolean conditions one level deep:
ComponentAttributeBag::macro("cn", function ( ...$args ): ComponentAttributeBag { /** @var ComponentAttributeBag $this */ $attr = $this->get("class", ""); $attr .= collect($args)->reduce(function (string $carry, mixed $arg) { if (!$arg) { return $carry; } if (is_array($arg)) { $reduced = collect($arg) ->filter(fn(mixed $boolish) => !!$boolish) ->map(fn(mixed $a, mixed $b) => is_numeric($b) ? $a : $b) ->join(" "); return $carry . " " . $reduced; } return $carry . " " . $arg; }, ""); $this->offsetSet("class", twMerge($attr)); return $this; });
So the usage is:
$attributes->cn([....]) // ?
So the usage is:
$attributes->cn([....]) // ?
Yep. Please see examples in my opening post
can we have a $attributes->cnFor
mixing what you did with twMergeFor
?
can we have a
$attributes->cnFor
mixing what you did withtwMergeFor
?
Ah nice, if it's already a thing then awesome.
Coming from a JavaScript background we have packages such as
clsx
which when combined withtailwind-merge
allows us to create a conditional class function that deals with merges as well.For example:
which would output either:
Laravel describes a similar behaviour with their built-in class handling called "Conditional Merge Classes" (docs).
But when applying the same to
twMerge
it seems like the original behaviour fromclass
is ignored:Would we be able to have the original behaviour built into the package to allow for conditional classes?