【问题标题】:Rails 7 and Tailwind dynamic classesRails 7 和 Tailwind 动态类
【发布时间】:2022-03-08 18:41:01
【问题描述】:

我有一个顺风的 Rails 7 应用程序,我正在做这样的事情:

@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 %>

视图生成正确的 HTML (ex: &lt;div class="w-6/12"&gt;),但浏览器无法识别这些类。如果我在不传递变量的情况下对它们进行硬编码,那么一切正常。我做错了什么或遗漏了什么?

【问题讨论】:

    标签: ruby-on-rails tailwind-css ruby-on-rails-7


    【解决方案1】:

    如果有人遇到同样的问题,请联系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,我在tailwind.config.js 中添加了一个动态变量列表,它工作正常,但您需要确保所有动态变量都在那里。

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

    【讨论】:

      【解决方案2】:

      动态创建类是行不通的。一个例子:

      # application_helper.rb
      
      def badge(text, color)
        tag.div text, class: "… bg-#{color}-500 …"
      end
      
      # show.html.erb
      
      <%= badge('Completed', 'green') %>
      

      这不会在构建中生成bg-green-500 类,因为构建过程仅按原样扫描 html.erb 文件,而不是在处理它们时。所以它永远不会看到 bg-green-500 类。

      【讨论】:

        猜你喜欢
        • 2022-06-18
        • 2021-02-17
        • 2022-01-20
        • 1970-01-01
        • 2021-10-23
        • 2022-07-13
        • 1970-01-01
        • 2022-08-06
        • 1970-01-01
        相关资源
        最近更新 更多