最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I give a variable to a Jade mixin with multiple arguments? - Stack Overflow

programmeradmin1浏览0评论

I'd like to create a variable that contains all the arguments of a mixin then pass the variable to the mixin. Is this possible and if so, why doesn't this work?

- var foo = "'arg1','arg2','arg3'"

mixin bar(arg1, arg2, arg3)
  div 
    #{arg1}, #{arg2}, #{arg3}

+bar(foo)

I'd like to create a variable that contains all the arguments of a mixin then pass the variable to the mixin. Is this possible and if so, why doesn't this work?

- var foo = "'arg1','arg2','arg3'"

mixin bar(arg1, arg2, arg3)
  div 
    #{arg1}, #{arg2}, #{arg3}

+bar(foo)
Share Improve this question asked Mar 3, 2013 at 21:36 Kyla MedinaKyla Medina 411 silver badge2 bronze badges 2
  • Why is there a + in front of bar(foo)? Also, foo is a string thus one variable. bar is expecting 3 variables. That is why it does not work! – Amberlamps Commented Mar 3, 2013 at 21:42
  • It looks like you need a plus sign in front. From the examples in the documentation jade-lang./reference/mixins – jackdbernier Commented Dec 8, 2014 at 3:27
Add a ment  | 

2 Answers 2

Reset to default 6

What you're trying does not work because you're using a string as single argument and invoke your bar mixin with a single string. You don't split the string arguments at the ',' character so only your arg1 contains a value.

First let's repair your bar mixin

mixin bar(args)
  div
    each arg in args
      | #{arg}

The code uses only one argument named 'args'. For this argument some enumerable or array like type is expected. See jade documentation for more information about iterations. The code block | #{arg} writes the arg value as plain text.

How to invoke this mixin? Instead of providing an argument as string you'll need to provide an argument array:

mixin bar(['arg1','arg2','arg3'])

In case you want to pass a string as argument you'd have to rewrite your mixin bar:

mixin barString(argString)
  - args = argString.split(',');

  div
    each arg in args
      | #{arg}

Then you could call the barString mixin:

mixin barString("arg1,arg2,arg3")

Note that I've removed the single quotes for this call.

This is late, you can also do it like this

mixin bar(...args)
    each arg in args
        | #{arg}

+bar('arg1', 'arg2', 'arg3')
发布评论

评论列表(0)

  1. 暂无评论