jinja2 - 如何使用 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
解决方案
这确实是一个范围问题。处理此问题的一种“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") }}
推荐阅读
- influxdb - 如何获得流入数据库中的下一个值
- c# - 根据 .NET Core 中的前 16 个字符从 Stream 反序列化 JSON
- pycharm - PyCharm:检查 PC 速度的数字
- arrays - 如何向下拖动公式并将某些行留空,但按顺序计算数字?
- javascript - 简单的条件路由
- angular - cdkDropTable 错误无法读取未定义的属性“_getSiblingContainerFromPosition”
- c# - 如何解决请求与 .Net Core Web Api 中的多个端点匹配的问题
- macos - Appium客户端无法本地连接到Appium服务器
- docker - 使用 WSL 上的 docker-compose 安装的卷仅部分出现并且为空
- reactjs - 如何为仅将 props 传递给 Child 的组件定义 propTypes