'Rails 7 and Tailwind dynamic classes

I have a Rails 7 app with tailwind where I'm doing something like this:

@list = [{name: "Some", width: "3/12"}, {name: "other", width: "6/12"}]

# In the view
<%= render 'mypartial': list: @list %>

# In the partial
<% list.each do |item|%>
  <div class="w-<%= item[:width] %>">
    <%= item[:name] %>
  </div>
<% end %>

The view generates the proper HTML (ex: <div class="w-6/12">), but the classes are not recognized in the browser. If I hard code them without passing the variable, everything works fine. Am I doing something wrong or missing something?



Solution 1:[1]

In case someone has the same issue, this is from the doc.

## Class names must be spelled out

For Tailwind to work, your class names need to be spelled out. They can't be programmatically composed. So no "text-gray-#{grade}", only "text-gray-500".

Atm, I added a list of dynamic variables in tailwind.config.js and it works ok, but you need to make sure all the dynamic variables are there.

  purge: {
    safelist: [
     w-1/12,
     ....
    ],
  },

Solution 2:[2]

Having dynamically created classes wont' work. An example:

# application_helper.rb

def badge(text, color)
  tag.div text, class: "… bg-#{color}-500 …"
end

# show.html.erb

<%= badge('Completed', 'green') %>

This won't generate the bg-green-500 class in the build because the build process only scans the html.erb files as is, not when they are processed. So it never sees the bg-green-500 class.

Solution 3:[3]

You can also add the dynamic classes as a comment in your templates, if you know what options you need. I am trying this approach, since that way my dynamic styles are right next to where I use them.

Here Slim code:

/ To force tailwind to recognize the dynamic styles to apply
/ .hidden.pl-2.pl-4.pl-6

Despite the comment, meaning no render to HTML, Tailwind still picks it up nicely.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guiddoo
Solution 2 Carl Sastre
Solution 3 Houen