Search code examples
sqljinja2dbt

How to use expressions in if statements in DBT


I want to know how, if possible, I can use dbt expressions that are enclosed in two curly brackets ({{ }}), inside a statement that is enclosed in a curly bracket and a percent sign ({% %}).

For example, I want to execute a piece of code in DBT if the table exists. In my head, it would look something like:

{% if {{this}} is not none %}

    do something

{% endif %}

But there's a syntax issue here and I can't seem to be able to use expressions inside statement blocks. I have seen the following implementation but I want to know how I can replace source with {{this}}.

{% set table_exists=source('db', 'table') is not none %}

{% if table_exists %}

   do something

{% endif %}

These are the docs I have read:



Solution

  • Don't Nest Your Curlies

    If you're inside either {{ ... }} or {% ... %}, your code will be executed by the jinja templating engine. this is a variable that is already set in the jinja context. You use {{ this }} in SQL, but if you're already in the jinja context provided by {% ... %}, you can just write this, without the curlies.

    Your if block becomes:

    {% if this is not none %}
    
        do something
    
    {% endif %}