Applying nested object of attributes in Jade/Pug

瘦欲@ 提交于 2019-12-19 21:47:03

问题


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&attributes({aria:{foo:'bar'}})

But none of these output the desired attribute notation. The first and third place an object literal in the base data/aria attribute. The second is a syntax error.

The only ways that I can find that work are:

div(data-foo='bar')

div&attributes({'aria-foo':'bar'})

回答1:


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)


来源:https://stackoverflow.com/questions/38212403/applying-nested-object-of-attributes-in-jade-pug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!