@php
$color = "red";
@endphp
<p class="text-{{$color}}-500">hello </p>
I use laravel and tailwindcss and vite.
When I open this page, the text-red-500 class is applied to this p tag, but it does not work, and the hello text is displayed with the default color. How can I solve this problem?
2
Answers
If the class names are not fully visible in the file, tailwind will ignore it.
This is the correct usage. For more information, you can check out tailwindcss page (https://tailwindcss.com/docs/content-configuration).
same answer as given here. Tailwind does not recognize dynamically generated classes. You need to explicitly define the color like
text-red-500
for the Tailwind parser to build the appropriate css for that class.There are ways around handling dynamic classes and they are suggested in the official documentation. You have to pick the best one for your use-case.
In this case, maybe you should do something like this:
I have put a list of possible colors in an array (assuming they are known), then in your backend or wherever data is coming from, you can set the index of the right color in the array like I have done with
$colors[2]
Change2
to the variable that holds the color index.This way, tailwind recognizes the class names upon run/build time and then generates their corresponding css.
Last resort would be to use the Tailwind safelist option which allows you to pre-define classes that must be built always. Again, this assumes that you know all the possible color combinations. Just add them there and tailwind will always add them to the built css.
I hope these options help to resolve your problem.
Cheers!