aLeal
aLeal

Reputation: 11

Jinja loop variable as macro variable?

I have the following loop in a dbt-spark model:

{% for day_hour in day_hours %}
     , {{ get_time(3, '{{day_hour}}') }} AS open_{{day_hour}}
{% endfor %}

Where day_hours is a list of integers from 0 to 23 (already defined) and get_time is a macro defined as

{% macro generate_timestamp(days, hours) %}
     DATE_TRUNC('day', CURRENT_TIMESTAMP - interval '{{ days }}' day) + interval '{{ hours }}' hour
{% endmacro %}

The problem is that in the call to the macro the {{ day_hour }} appears as a string as it is written, instead of returning the corresponding number. If I remove the single quotes around {{ day_hours }} it throws a compilation error.

However, In the second call to {{ day_hour }} within the loop:

AS open_{{day_hour}}

It works perfectly.

Does anyone know if it is possible to use the loop variable as macro parameter??

Thank you very much in advance for your help!

Upvotes: 1

Views: 585

Answers (1)

tconbeer
tconbeer

Reputation: 5805

Don't nest your curlies.

Your call to get_time is already wrapped in curlies, so you can just write day_hour to reference the jinja variable:

{% for day_hour in day_hours %}
     , {{ get_time(3, day_hour) }} AS open_{{day_hour}}
{% endfor %}

Upvotes: 1

Related Questions