Clearer mixins in Jade / Pug
I am looking for ways to display mixin arguments explicitly in Jade / Pug.
Here is some pseudo code to illustrate what I mean:
// Current situation
+c-button('Button label', 'overstated', 'large')
// Here we can see what the mixin expects
+c-button(btnLabel: 'Button label', btnType: 'overstated', btnSize: 'large')
Thus, the mixin provides an "API". This makes copy / passive / modifiable code for people who don't understand every internal mechanic of the code.
(I found out that this is actually implemented in the mop stories, PHP pug implementation -> https://sandbox.pug.talesoft.codes/?example=named-mixin-parameters )
What I get are legible mixins. I don't care how this is implemented as long as the end result is easy to use.
Another idea is to add one options object to the mixin.
Now this code I have compiled doesn't work at all. Looking for a Javascript expert to shed some light here :)
mixin c-button({options})
- {
[
option1: true
]
}
a.c-button(href="#") #{btnLabel}
// Code does not actually work because mixins can't take objects?
+c-button({ option1: false })
source to share
You can use the options object to simulate named arguments. You can also use Object.assign()
to combine parameters with a predefined optional object to simulate the default parameters:
mixin button (options)
- var DEFAULT_OPTIONS = { type: 'button', variant: 'default' };
- options = Object.assign({}, DEFAULT_OPTIONS, options || {});
button(class='btn--' + options.variant, type=options.type)= options.label
+button({ label: 'foo' })
See a working example at https://codepen.io/thomastuts/pen/JNVWYX .
source to share