首页 > 解决方案 > 如何使用 Jinja for 循环连接字符串?

问题描述

我正在尝试迭代地连接一个字符串以使用“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

标签: jinja2email-templatessendwithus

解决方案


这确实是一个范围问题。处理此问题的一种“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") }}

推荐阅读