0

I made a component and I want it to be in different colors.

If I don't pass a color I want default to be blue.

I managed to do that with the following:

<div class="text-{{$color ?? 'blue'}}-400"></div>

But now I have a problem when I am checking 2 cases:

<div class="{{ isset($bg) ? "text-{$color ?? 'blue'}-100" : "text-{$color ?? 'blue'}-600" }}"></div>

If background image is set - show text in passed color in shade 100. If there's no bg image set text in shade 600. (If no color is passed use default 'blue' shade)

I am getting this error:

syntax error, unexpected '??' (T_COALESCE), expecting :: (T_PAAMAYIM_NEKUDOTAYIM)

2 Answers 2

2

The string concatenation won't work when purging your CSS. During the purge, it won't consider your logic (it only reads strings as they are) so the classes most likely will be purged. This is mentioned in TailwindCSS docs.

My recommendation is to store that in a blade component and just use a switch-case statement to create the variations. It leads to repetition but at least you will have all that stored in only one place:

@switch($color ?? null)
  @case('red')
    <div class="{{ isset($bg) ? 'text-red-100' : 'text-red-600' }}"></div>
    @break

  @case('green')
    <div class="{{ isset($bg) ? 'text-green-100' : 'text-green-600' }}"></div>
    @break

  @default
    <div class="{{ isset($bg) ? 'text-blue-100' : 'text-blue-600' }}"></div>
@endswitch
Sign up to request clarification or add additional context in comments.

Comments

0

I had the same issue with my project, I decided to see if adding a comment to my php file with the css variables would work and it did so i saved the switch statement and just inserted :

<!-- bottom-2 top-2 right-2 left-2 -->

Tailwind did then compile with the variables i needed with ccs nano enabled.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.