Reid Williams
Reid Williams

Reputation: 381

Can dbt macros accept other macros as arguments?

I am curious if I can pass macros into another macro like this:

{% macro my_macro(a, b, another_macro) %}
  ...
  {{ another_macro(a,b) }}
  ...
{% endmacro %}

BONUS: If dbt's framework can allow it am able to how can I pass arguments to it?

In R it would look like

my_callable_function <- function(another_function, ...) {
  another_function(...)
}

Upvotes: 9

Views: 11044

Answers (2)

trillion
trillion

Reputation: 1401

i am not sure but if you are calculating something in dbt for example

{% macro sum_of_two_columns(a, b) %}
  a + b
 
{% endmacro %}

then in your model file you will have something like

select 
revenue1,
revenue2,
{{ sum_of_two_columns('revenue1','revenue2') }} as total_revenue

from [table]

now you can pass the total_revenue in your second macro that you would like to create: for example:

{% macro subtracting_column(a) %}
  a - 100
{% endmacro %}

finally you can use it :

    select 
    revenue1,
    revenue2,
    {{ sum_of_two_columns('revenue1','revenue2') }} as total_revenue,
    {{ subtracting_column('total_revenue') }} as adjusted_revenue
    
    from [table]

In short you will be passing the results of one macro to another which is what you want

Upvotes: 2

Reid Williams
Reid Williams

Reputation: 381

A conversation on dbt cloud's slack and a bit of poking and prodding yielded me the answer.

Yes you can pass nested macros into a macro much like nested functions in different languages!

An example could look like this!

{% macro base_macro(func1, arg1, arg2) %}
  {{ func1(arg1, arg2) }}
{% endmacro %}

Upvotes: 12

Related Questions