skip to Main Content
@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


  1. If the class names are not fully visible in the file, tailwind will ignore it.

    The way Tailwind scans your source code for classes is intentionally very simple — we don’t actually parse or execute any of your code in the language it’s written in, we just use regular expressions to extract every string that could possibly be a class name.

    @php
    
    $color = "text-red-500";
    
    @endphp
    
    <p class="{{$color}}">hello </p>
    

    This is the correct usage. For more information, you can check out tailwindcss page (https://tailwindcss.com/docs/content-configuration).

    Login or Signup to reply.
  2. 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:

    @php
    
    $colors = ["text-red-500", "text-blue-500", "text-green-500", "text-yellow-500", "text-purple-500"];
    
    @endphp
    
    <p class="{{$colors[2]}}"> hello </p>
    

    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] Change 2 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search