Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jinja2 如何使用Jinja for循环连接字符串?_Jinja2_Email Templates_Sendwithus - Fatal编程技术网

Jinja2 如何使用Jinja for循环连接字符串?

Jinja2 如何使用Jinja for循环连接字符串?,jinja2,email-templates,sendwithus,Jinja2,Email Templates,Sendwithus,我试图迭代地连接一个字符串,以构建带有“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(a

我试图迭代地连接一个字符串,以构建带有“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
我还尝试了namespace(),但没有成功:

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

这确实是一个范围问题。处理这个问题的一种“黑客”方式是使用一个你附加在下面的列表:

{% 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" #}
上面的内容可以满足您的需要,但是对于这个特定的示例,我将看看如何使用。它更具声明性,感觉不那么刺耳

{% 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") }}

谢谢,迪伦!你的第二个解决方案非常有效!我不知道join接受了多个参数。第一个解决方案在没有{%set url_param=url_param~param%}的情况下工作,但我确信这是一个输入错误。实际上,我尝试了类似的解决方案,但认为在追加数组时必须调用“do”。