Search code examples
ruby-on-railstailwind-css

TailwindCSS arbitrary value in Rails view


In a Rails 7 app with TailwindCSS (with the tailwindcss-rails gem), I have the car model with the color attribute stored as hexadecimal colors (i.e. #a565cc).

According to TailwindCSS documentation, it's possible to define an arbitrary value notation to generate a class for that color on-demand (i.e. <button class="bg-[#1da1f2] ...">...</button>).

So, I have added in my view bg-[<%= car.color %>], which in Firefox inspector renders correctly,

enter image description here

But in the browser, the button doesn't have a background.

My Tailwind config looks like

module.exports = {
  content: [
    './public/*.html',
    './app/helpers/**/*.rb',
    './app/javascript/**/*.js',
    './app/assets/images/*.svg',
    './app/views/**/*.{erb,html}'
  ]
 ...
}

Am I missing something here?


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-600 and text-green-600 do 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 the style attribute instead, like:

    <button class="…" style="background-color: <%= car.color %>">