1

As nunjucks now supports using set as a block I wanted to do something like this:

{% set navigationItems %}
  {% for item in items %}
    { name: item.name, url: item.url }{% if not loop.last %},{% endif %}
  {% endif %}
{% endset %}

Then call this variable as the input object on another macro, like so:

{{ navigation(items=[navigationItems]) }}

However, navigationItems is evaluated as a string, not an array-literal. Any idea how, or if this is possible?

Thanks.

4

1 回答 1

6

我不确定您要完成什么。看起来您想遍历一个名为的数组items并将其复制到一个名为navigationItems. 可能items包含比您想要传递给宏更多的键?

我将做出这样的假设,否则您可以像这样简单地items复制navigationItems

{% set navigationItems = items %}

这个例子有效:

{% macro navigation(items) %}
    <ul>
        {% for item in items %}
            <li>{{ item.name }} - {{ item.url }}</li>
        {% endfor %}
    </ul>
{% endmacro %}

{% set websites = [
    {
        name: 'Google',
        url: 'http://google.com',
        description: 'A search engine'
    },
    {
        name: 'GitHub',
        url: 'http://github.com',
        description: 'A webapp for your git repos'
    },
    {
        name: 'StackOverflow',
        url: 'http://stackoverflow.com',
        description: 'The answer: 42'
    }] %}

{% set navigationItems = [] %}
{% for website in websites %}
    {% set navigationItems = (navigationItems.push({name: website.name, url: website.url}), navigationItems) %}
{% endfor %}

{{ navigation(items=navigationItems) }}

websitesvalues 包含一个description未传递给navigationItems数组的键。如果是我,我会直接传递websitenavigation宏,因为你的键:name并且url在两个数组中都是相同的。

这里的模式几乎就像mapJavascript 或 Ruby 中的方法。

于 2017-08-24T03:09:28.260 回答