6

我正在尝试迭代地连接一个字符串以使用“for”循环构建 url 参数,但我相信我遇到了范围问题。

The output should be: url_param = "&query_param=hello&query_param=world"

array_of_objects = [{'id':'hello'},{'id':'world'}]

{% set url_param = "" %}

{% set array_of_ids = array_of_objects|map(attribute='id')|list%} // correctly returns [1,2]

{% for id in array_of_ids %}
   {% set param = '&query_param='~id %}
   {% set url_param = url_param~param %}                             
{% endfor %}

//url_param is still an empty string

我也尝试了命名空间(),但无济于事:

{% set ns = namespace() %}
 {% set ns.output = '' %}
 {% set array_of_ids = array_of_objects|map(attribute='id')|list%} // correctly returns [1,2]
{% for id in array_of_ids %}
   {% set param = '&industries='~id%}
   {% set ns.output = ns.output~param %}                             
{% endfor %}
//ns.output returns namespace
4

2 回答 2

7

这确实是一个范围问题。处理此问题的一种“hacky”方法是使用您附加到的列表,如下所示:

{% set array_of_objects = [{'id':'hello'},{'id':'world'}] %}

{% set array_of_ids = array_of_objects|map(attribute='id')|list%}

{{ array_of_ids|pprint }} {# output: ['hello', 'world'] #}

{% set ids = [] %}  {# Temporary list #}

{% for id in array_of_ids %}
   {% set param = '&query_param='~id %}
   {% set url_param = url_param~param %}
   {{ ids.append(url_param) }}
{% endfor %}

{{ ids|pprint }} {# output: [u'&query_param=hello', u'&query_param=world'] #}
{{ ids|join|pprint }} {# output: "&query_param=hello&query_param=world" #}

以上为您提供所需的内容,但对于这个特定示例,我将看看使用jinja 的 join filter。它更具声明性,感觉不那么骇人听闻。

{% set array_of_objects = [{'id':'hello'},{'id':'world'}] %}

{# set to a variable #}
{% set query_string = "&query_param=" ~ array_of_objects|join("&query_param=", attribute="id") %}

{{ query_string|pprint }}
{# output: u'&query_param=hello&query_param=world'  #}

{# or just use it inline #}
{{ "&query_param=" ~ array_of_objects|join("&query_param=", attribute="id") }}
于 2018-12-12T04:22:50.837 回答
0

您应该更改命名空间的初始化。这是文档中的一个示例,可以帮助您:

{% set ns = namespace(found=false) %}
{% for item in items %}
    {% if item.check_something() %}
        {% set ns.found = true %}
    {% endif %}
    * {{ item.title }}
{% endfor %}
Found item having something: {{ ns.found }}
于 2021-10-07T10:41:12.570 回答