0
0
dbtdata~5 mins

Calling macros across projects in dbt

Choose your learning style9 modes available
Introduction

Sometimes you want to reuse code from another project to save time and keep things neat. Calling macros across projects lets you do that easily.

You have a common calculation macro in one project and want to use it in another project.
You want to keep shared logic in a central project and call it from multiple other projects.
You are working on multiple dbt projects and want to avoid copying the same macro code.
You want to update a macro in one place and have all projects use the updated version automatically.
Syntax
dbt
{{ project_name.macro_name(args) }}

You use the project name as a prefix to call the macro from another project.

Make sure the other project is listed as a dependency in your packages.yml file.

Examples
This calls the calculate_discount macro from the other_project project, passing price and discount_rate as arguments.
dbt
{{ other_project.calculate_discount(price, discount_rate) }}
This sets a variable result by calling the format_date macro from the external_project.
dbt
{% set result = external_project.format_date(order_date) %}
Sample Program

This example shows how to add a shared macros project as a package, then call its calculate_tax macro in your model SQL.

dbt
# In packages.yml of your current project:
packages:
  - git: "https://github.com/your_org/shared_macros.git"
    revision: main

# In your model SQL file:
{{ shared_macros.calculate_tax(price, tax_rate) }}

# In shared_macros project, macro defined as:
# {% macro calculate_tax(price, tax_rate) %}
#   {{ price * tax_rate }}
# {% endmacro %}
OutputSuccess
Important Notes

Always add the external project to packages.yml and run dbt deps to install it.

Macros must be public (not private) to be called across projects.

Use the exact project name as defined in dbt_project.yml of the external project.

Summary

Calling macros across projects helps reuse code and keep projects clean.

You must add the other project as a dependency in packages.yml.

Use {{ project_name.macro_name(args) }} syntax to call the macro.