ArrayKnight ArrayKnight - 4 months ago 69
Node.js Question

Applying nested object of attributes in Jade/Pug

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'})

Answer

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)
Comments