在 DBT 中是否有一种干净的方法来连接 for 循环?

Ala*_*lan 1 dbt

考虑一下我写的这个宏:

{% macro concatenate_columns() %}

    {% for column in [col_1, col_2, col_3] %}

    "{{column}}" ||

    {% endfor %}
    ''

{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

该宏的要点是获取一个列数组并将它们连接在一起。但是,在之后{% endfor %}我必须包含 a''以防止宏将最终字符返回为||

这是我在 for 循环中遇到的一个常见问题。这在语法上并不难处理,但我遇到过一种情况,我UNION在循环之间使用了 s,并且最后添加的位变得非常复杂。

是否有一种干净的方法来编写 for 循环,其中最终循环“束缚”输出,并且不继续附加?

Ale*_* CC 5

在 Jinja 中,您可以使用该{% if [not] loop.last %}位,让程序知道每当您处理循环中的最后一次迭代(或除最后一次之外的所有迭代,因此在其中[not])时,您需要不同的行为。

例如,在您的示例中,您可以使用以下内容:

{% macro concatenate_columns() %}

    {% for column in [col_1, col_2, col_3] %}

      "{{column}}" {% if not loop.last %} || ' ' || {% endif %}

    {% endfor %}

{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

应该编译为: col_1 || ' ' || col_2 || ' ' || col_3

这样,只要您不在循环的最后一次迭代中,您就会在代码中for添加 concat ( ||) + space ( ' ') + concat ( ) 。||