skip to Main Content
            @foreach ($tags as $tag)
                <a href="#" class="text-{{$tag->color}} bg-{{$tag->color}}/20 text-center p-2 rounded-full">#{{$tag->name}}</a>   
            @endforeach

I’m trying to show some hashtags with the correct name and color being pulled from a database. The info is all there, but for some reason, the colors do not work when being set like this. They show up as classes when inspecting, but have no effect.

<a href="#" class="text-blue-500 bg-blue-500/20 text-center p-2 rounded-full">#roleplay</a>

If I remove the {{}}’s and enter the color manually, as it is in the database, the colors show up correctly. Also worth a mention that sometimes the color would show up for one a tag, but not for the others.

2

Answers


  1. Tailwind doesn’t handle dynamic class names well and even says in its documentation to not construct class names dynamically.

    What you could do is either store the entire tag class in your database (text-blue-500), or store just the colour and construct the class name in your controller then provide that to your view as part of the tag data.

    Login or Signup to reply.
  2. From the tailwind documentation, dynamically generated class names must be explicitly included in their safelist.

    tailwind.config.js

    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      safelist: [
        'text-2xl',
        'text-3xl',
        {
          pattern: /bg-(red|green|blue)-(100|200|300)/,
        },
      ],
      // ...
    }
    

    The above config will allow for exceptions of specific tags – like text-2xl or those following a regex pattern.

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