Wolfr
Wolfr

Reputation: 5164

Clearer mixins in Jade/Pug

I am looking for ways to display the arguments of a mixin 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')

This way the mixin exposes the "API". This makes for copy/pastable/modifiable code for people who don't understand every inner mechanic of the code.

(I found out this is actually implementd in tales of pug, a PHP implementation of pug --> https://sandbox.pug.talesoft.codes/?example=named-mixin-parameters)

What I am after is legible mixins. I don't care how it is implemented as long as the end result is easy to use.

Another idea is to add a single options object to a mixin.

Now, this code that I made up does not 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 })

Upvotes: 3

Views: 441

Answers (1)

thomastuts
thomastuts

Reputation: 3539

You can use an options object to simulate named arguments. You can also use Object.assign() to merge the options with a predefined options object to simulate option defaults:

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.

Upvotes: 4

Related Questions