LoginSignup
11
10

More than 5 years have passed since last update.

BEMを最短で書くためのMixin

Last updated at Posted at 2015-12-11

BEMするの大変ですよね〜。

Jadeでこんな感じに書くと、

Jade
include jade-de-bem

+div(class="block --special")
  +ul(class="__items div")
    +li(class="__item --new div")
      +a(class="__link span")
        | Foo

こう変換される、

HTML
<div class="block block--special">
  <ul class="block__items div">
    <li class="block__item block__item--new div">
      <a class="block__link span">Foo
      </a>
    </li>
  </ul>
</div>

Mixinを作りました。

Jade
mixin bem(boo)

  -
    var config = {}
    config.element  = '__'
    config.modifier = '--'

    function converted(str) {
      arr = str.split('')
      res = arr.join('\\')
      res = '^' + res
      return res
    }

    var elmExamStr = converted(config.element)
    var modExamStr = converted(config.modifier)

    var elmExam = new RegExp(elmExamStr)
    var modExam = new RegExp(modExamStr)

    var tag = attributes.tag ? attributes.tag : false
    var cls = attributes.class ? attributes.class + '' : ''

    attributes.tag = null
    attributes.class = ''

    bem = bem || []
    var elm = ''
    var mod = []
    var els = []
    var res = []
    var str = ''

    function hasLength(str) {
      return (str.length)
    }

    var names = cls.split(' ')
    names = names.filter(hasLength)

    for (var i=0; i<names.length; i++)
      if (elmExam.test(names[i]))
        elm = names[i]
      else if (modExam.test(names[i]))
        mod.push(names[i])
      else if (i === 0)
        bem.push(names[i])
      else
        els.push(names[i])

    if (boo === false)
      bem.pop()

    var len = bem.length - 1

    if (elm.length)
      res.push(bem[len] + elm)
    else
      res.push(bem[len])

    for (var i=0; i<mod.length; i++)
      if (elm.length)
        res.push(bem[len] + elm + mod[i])
      else
        res.push(bem[len] + mod[i])

    for (var i=0; i<els.length; i++)
      res.push(els[i])

    str = res.join(' ')
    attributes.class = str

  if (tag && boo !== false)
    #{tag}&attributes(attributes)
      block

  if (boo === true)
    block

Enjoy BEM Life!

11
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10