我有类似的哈希:
hash = {"body"=>{"background_color"=>"#d6e9c6"}, "control_label"=>{"font_family"=>"arial", "font_size"=>"12px"}}
如何将其转换为这样的CSS规则?
body {
background-color: d6e9c6
}
.control_label {
font-family: "Arial";
font-size: "12px"
}
到目前为止,已经完成了此操作,但是遇到了麻烦,任何帮助都将是非常有用的。
hash.map {|k,v| "#{k} #{v.keys.map(&:dasherize)}"}.join("\n")
在页面上这样做,就像这样。
<% hash.each do |rule,styles| %>
<%= rule %> {
<% styles.each do |k,v| %>
<%= k %>: <% v.inspect %>;
<% end %>
}
<% end %>
您可以将此作为hash
局部变量,也可以作为局部变量,也可以为其提供帮助:
def hash_to_css(hash)
lines = []
hash.each do |rule,styles|
lines << "#{rule} {"
styles.each do |k,v|
lines << " #{k}: #{v.inspect};"
end
lines << "}"
end
lines.join("\n")
end
现在,您可以在页面上说
<%= hash_to_css(@my_css_hash) %>
编辑:正如@mudosowba在评论中指出的那样,为了使其正常工作,“输入”信息首先必须正确。即,您需要将其".control_label"
作为哈希键而不是"control_label"
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句