motinska94's avatar

Tailwind classes don't work in blade with variables ( bg-{{$color}}-400 )

I had following code in my blade file, $color variable has values like red, cyan, gray etc, which all are colors that exist in Tailwind.

<div class="bg-{{$color}}-400">
Hello world
</div>

However when I run the code, refresh the page, even re-run npm run dev, it didn't give my div the proper background color. Until I did it manually, like I rewrote the code as following :

<div class="bg-red-400">
Hello world
</div>

And it was working, and when I changed it back to the original code (with variable) it kept working with red, but the other colors weren't working. So I had to manually add all the colors in as class names, refresh the page and re-change the code to use the variable as color name and now it's working as expected.

Did I do something wrong? Is this a bug in Blade, or Tailwind? Did I not run npm run dev properly? What should I do to avoid this from happening in the future? Because I spent last 3 hours of my life on this and I don't want to face the same error again.

Apart from re-running npm run dev, I also ran php artisan view:clear and php artisan config:clear as well.

Thanks.

0 likes
6 replies
motinska94's avatar

Update : I found the answer

Short answer : Apparently you can't use it like bg-{{$color}}-400, you need to give the whole class name like $bgColorClass => bg-red-400.

freddyqt's avatar

@motinska94 Could you achieve it? I wanted to call the color styles from the serviceprovider to make them dynamic, but I didn't have success :(

1 like
motinska94's avatar

@freddyqt I saw this 2 days later, I don't know if you're still looking for a solution but..

I solved it the way I said in this comment, however there's another way, you can use them dynamically by Safelisting them.

Nothing too complicated, just add an array to your module.exports in tailwind.config.js file. Here's an example from tailwind documentation.

,
  safelist: [
    'bg-red-500',
    'text-3xl',
    'lg:text-4xl',
  ]
2 likes

Please or to participate in this conversation.