Output variable only if defined

I’m trying to output a dbt variable into a jinja template conditional on that variable being defined. Alas, my naive attempt does not seem to work:

{% if var('my_variable') is defined %}WHERE f.source_date < '{{ var('my_variable') }}'::DATE{% endif %}

It is hard to know how you are defining it, under what conditions it will be defined, etc. But with the very little information provided, maybe this will help?

Just use Boolean instead. Start the model with:

{% set my_variable = False %}

Then at some point in your script you flip it to true under certain circumstances?

Try this website to play with it! http://jinja.quantprogramming.com/

Update:
If you just get rid of “Is defined” it should work. Just make sure when you define it, you define it as “True”:

I was just re-reading this and realized your variable needs to be used in a date comparison. The same answer applies though:

vs

Sorry, I should have been far clearer: The kinds of variables I want to be able to (optionally) use are the ones I pull via var(), not local jinja variables.

It works the same way but you just refer to it differently.