Liad Tau
Liad Tau

Reputation: 51

Jinja2 set default value to include if failed

I'm trying to run this:

{%- include '{name}.sql'.format(name=name) -%}

but the thing is, from time to time the files I will try to include won't exist.

I've found this as a solution to catch the exception and return value:

{%- include '{name}.sql'.format(name=name) ignore missing -%}

and it does catch the exceptions, but the thing is that it has a default value of '',

How can I set the default value of whatever I want?

Upvotes: 1

Views: 188

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39129

As raised in the documentation:

You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception.

Source: https://jinja.palletsprojects.com/en/3.0.x/templates/#include

So if you do have a file, let's say default.sql that you know from a fact exists, you could do:

{%- include ['{name}.sql'.format(name=name), 'default.sql'] -%}

Upvotes: 1

Related Questions