Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support spread operator in macro/function arguments #1269

Open
Snugug opened this issue Mar 2, 2020 · 3 comments
Open

Support spread operator in macro/function arguments #1269

Snugug opened this issue Mar 2, 2020 · 3 comments

Comments

@Snugug
Copy link

Snugug commented Mar 2, 2020

I'm trying to dynamically pass in arguments to a macro without knowing either what the argument names are or how many arguments I may be getting. In ES6, the way to do this is to create an array and use the spread syntax. I'd like Nunjucks to support something similar, so I can do the following:

{{ myMacro(...myArrayOfArgs) }}

And have it be the same as

{{ myMacro(myArrayOfArgs[0], myArrayOfArgs[1], myArrayOfArgs[2]...) }}
@eklingen
Copy link
Contributor

eklingen commented Sep 11, 2020

Personally, I'd love a feature like a spread option, but perhaps in a more compatible way with Jinja.
In Jinja, you can use the python expansion operators like so:

{% macro myButtonMacro(href = '', title = '') %}
  <a href="{{ href }}">{{ title }}</a>
{% endmacro %}

{% set testlist = [ '?', 'click me' ] %}
{% set testdict = { 'href': '?', 'title': 'clickme' } %}

{{ myButtonMacro(href = testdict.href, title = testdict.title) }}
{{ myButtonMacro(*testlist) }}
{{ myButtonMacro(**testdict) }}

And these will render identical. However, as far as I know, this is undocumented behavior (in templates).

@kruncher
Copy link

I think it would need to also support JS style spread syntax even if the Python compatible syntax were supported because otherwise it would not be intuitive for people using just JS.

@edwardhorsford
Copy link

This would be so helpful for my usage - I frequently want to merge an object of params on to an object of defaults.

I can do merging with a custom filter, but it would be lovely to be able to do it natively like this:

{% set defaultOptions = {
  quantity: 5,
  price: "£4.5"
} %}

{% set options = {...defaultOptions, params} %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants