Applying nested object of attributes in Jade/Pug

前端 未结 1 796
醉话见心
醉话见心 2021-01-19 10:21

Is there a way to pass an object of data/aria attributes to an element?

I\'ve tried:

div(data={foo:\'bar\'})

div(data={foo=\'bar\'})

div&attrib         


        
相关标签:
1条回答
  • 2021-01-19 10:57

    By leading new lines with a minus - you are able to write regular JavaScript in JADE / PUG. This gives you a powerfull weapon to resolve almost everything.

    Just grab an regular object like var attributes = {'foo':'bar', 'bar':'foo'} and extend the keys of it in a for each loop with your desired prefix.

    Here is a working Pen http://codepen.io/pure180/pen/kXwqdA and this could be your code:

    - var attributes = {'foo':'bar', 'bar':'baz'}
    - var ariaAttributes = {}
    - for (attr in attributes) {
    -     var key = 'aria-' + attr
    -     ariaAttributes[key] = attributes[attr]
    - }
    
    div&attributes(ariaAttributes) Test
    

    You can also use it as an global mixin, here is the Pen http://codepen.io/pure180/pen/KrqYpB and it can looks then like this:

    mixin setAriaAttr(object)
      - var attributes = object
      - var ariaAttributes = {}
      - for (attr in attributes) {
      -     var key = 'aria-' + attr
      -     ariaAttributes[key] = attributes[attr]
      - }
    
      div&attributes(ariaAttributes) Test
    
    - var aria = {'foo':'bar', 'bar':'baz'}
    +setAriaAttr(aria)
    
    0 讨论(0)
提交回复
热议问题