Understanding What Are dbt Jinja Macros
Lab Steps
Introduction
dbt Jinja macros are a very helpful way to implement some logic in your dbt project.
In this lab step, you will understand what macros are and how to leverage them in dbt.
Introduction to Macros
Macros are functions written in Jinja, a powerful template language, that enables you to use classic programming language structures such as if/else and loops, access and leverage environment variables, and work over the results of queries expressed in the dbt models. By using macros, you define reusable logic that you can use in multiple parts of your dbt project. This way, you can avoid defining the same logic on multiple points.
There is two kinds of dbt macros:
- Native macros: Available by default in dbt (ex. source and ref)
- Custom macros: Custom Jinja functions defined by the user
To get the whole reference of Jinja macros, you can check out the official dbt docs.
Usage of dbt Macros
Every time you need to use a macro inside a transformation you are defining, you need to follow this syntax:
Copy code{{ macro_name(list of params) }}
The brackets are required in order to let dbt you want to access and use some Jinja part (in this case the Jinja content of the macro). Then you need to invoke the macro as it was a function by specifying parameters if there are.
Suppose you have a macro whose name is generate_random_values that accepts min and max parameters. You should have a piece of code similar to the following in order to invoke it:
Copy code{{ generate_random_values(1, 10) }}
Summary
In this lab step, you understood what macros are and how to leverage them in dbt.