This is my component in Laravel:
<div {{ $attributes->merge(['class' => "inline-flex items-center justify-center flex-shrink-0 w-8 h-8 text-$color-500 bg-$color-100 rounded-lg dark:bg-$color-500 dark:text-$color-200"]) }}>
<svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor"
viewBox="0 0 20 20">
<path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 8.207-4 4a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L9 10.586l3.293-3.293a1 1 0 0 1 1.414 1.414Z"/>
</svg>
<span class="sr-only">Check icon</span>
</div>
And I use it in view like this:
<x-toasts.toast color="amber">{{session(‘deleted’)}}</x-toasts.toast>
But when I use some colors like red, it works, and I have tested methods such as deleting the compiled views and even changing them using javascript, but it still didn’t work, but when I want, for example, from the same class I use it completely without manipulating the color variable. The colors work perfectly and the class is applied. Where is the problem?
>Solution :
As per the documentation:
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:
Don’t construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>In the example above, the strings
text-red-600andtext-green-600do not exist, so Tailwind will not generate those classes.
Instead, make sure any class names you’re using exist in full:Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
You could consider:
- Using full class names in definitions, like:
<x-toasts.toast color="bg-amber-100 text-amber-500 dark:bg-amber-500 dark:text-amber-200"><div {{ $attributes->merge(['class' => "inline-flex items-center justify-center flex-shrink-0 w-8 h-8 $color"]) }}> - Having a map of colors, like:
@php $colors = [ 'amber' => 'bg-amber-100 text-amber-500 dark:bg-amber-500 dark:text-amber-200', 'red' => 'bg-red-100 text-red-500 dark:bg-red-500 dark:text-red-200', // … ]; @endphp <div {{ $attributes->merge(['class' => "inline-flex items-center justify-center flex-shrink-0 w-8 h-8 $colors[$color]"]) }}> - Safelisting the classes that may be used, like:
/** @type {import('tailwindcss').Config} */ module.exports = { // … safelist: [ { pattern: /^bg-(amber|red|…)-100$/ }, { pattern: /^text-(amber|red|…)-500$/ }, { pattern: /^bg-(amber|red|…)-500$/, variants: ['dark'], }, { pattern: /^text-(amber|red|…)-200$/, variants: ['dark'], }, ], // ... }