mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.57k stars 639 forks source link

Support spread operator in macro/function arguments #1269

Open Snugug opened 4 years ago

Snugug commented 4 years ago

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 commented 4 years ago

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 commented 2 years ago

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 commented 9 months ago

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} %}