mardi 17 mai 2016

Simple way to implement programmatic css class name mapping with SASS / Rails 3

I'm trying to find a way to reduce the length of BEM based css class names by keeping a global mapping of class name mappings in the ruby code and referencing it from both the erb template and the scss file.

Is there a way to call a function which maps the css class name in SASS (eg the something and something_else functions below) or achieve the same result in an idiomatic way?

# template.html.erb

<%= content_tag(:div, css_block_name('section')) do %>
  <%= content_tag(a, 'Some content', class: css_elem_name('section', 'link') %>
<% end %>

# helper.rb

BLOCK_NAMES = {
  'section' => 'a'
}

ELEMENT_NAMES = {
  'link' => 'a'
}

def css_block_name(name)
  CLASS_NAMES[name]
end

def css_elem_name(block_name, element_name)
  "#{CLASS_NAMES[name]}__#{ELEMENT_NAMES[element_name]}"
end

# style.scss

something(.section) {
  background-color: green;

  & something_else(.link) {
    &:hover { 
      color: red;
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire