gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:11:22 25 4
gpt4 key购买 nike

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

最佳答案

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

关于jinja2 - 如何使用 Jinja for 循环连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com