Search code examples
pug

how to check if a passed arguement is a mixin


I have a mixin that takes another mixin (callback if you will) how to check if the passed argument is a mixin so that it doesn't break my code??

I tried

p #{mixins}  //- nothing gets outputed
p #{Object.keys(pug_mixins).length}  //- 0
p #{JSON.stringify(pug_mixins)}   // {}
p #{globals}  //- nothing gets outputed
// but in vain

and the funny thing is when I mistype the mixin on purpose when calling it
the error that gets logged starts with pug_mixins.templatee is not a function ¯\_(ツ)_/¯

edit: I also tried browsing the source code && the doc but nothing helped

edit2: it seems like it only works when wrapped in a function! why's that???

doesn't work

mixin myMixin()
    em smth

#container
    if pug_mixins['myMixin']
        h2 200
    else
        h2 404
//- 404
//- WHY????


Works

mixin myMixin
    h2 200:)!

-
    const typeCheck = val => {
        if (pug_mixins[val]) {
            return 'mixin'
        } else {
            return 'text'
        }
    }

mixin myMixin2(val)
    #container
        case typeCheck(val)
            when 'mixin'
                +#{val}()
            when 'text'
                p 404:')
            default
                p i hate my life

+myMixin2('myMixin')


Solution

  • This works for me:

    mixin bar(m)
      | before_
      if pug_mixins[m]
        +#{m}
      | _after
    
    mixin foo
      b foo
    
    +bar("foo")
    = " "
    +bar("baz")
    

    gives this output: before_<b>foo</b>_after before__after

    Note that pug_mixins is sensitive to the order of your code.

    Edited to add:

    You must also actually call the mixin at some point for the mixin name to be in pug_mixins. Note that in your not-working example, you check for the mixin's presence, but don't actually call it.