An option to ignore unknown variables
3fr61n opened this issue · comments
Hi
Nice project BTW...
I suggest to add an option in the command line to ignore when there is a undefined variable on the template, so this type of error won't occurs
jinja2.exceptions.UndefinedError: 'MY_UNKNOWN_VAR' is undefined
I think this will be helpful when you have multiple variable inputs for the same template, so I can execute things like.
j2 --ignore_unknown my_template.j2 input1.yaml | j2 --ignore_unknown my_template.j2 input2.yaml | j2 my_template.j2 input3.yaml
Regards
Hi there,
thanks for implementing this!
I found two problems, though. Maybe the issue can be reopened?
-
The undefined flag doesn't ignore unknown nested parameters. For instance {{ i }} is successfully ignored if "i" is undefined but {{ a.t }} throughs an exception if "a" is undefined.
-
The current implementation replaces unknown parameters with the empty string. This means that 3fr61n's example of piping multiple invocations of j2 won't work. I think it would be great if unknown parameters would stay in the file, i.e. if "i" is undefined, invoking j2 would replace {{ i }} with {{ i }}, so that later jinja2 runs can replace the remaining parameters.
BR Andreas
@akbo, the idea of keeping unknown variables "as is" may have its use, but in most cases will only lead to errors.
Suppose you've messed up your environment, and a variable that was previously available is now not set. Then j2cli
will not report any errors, and happily produce a file that is actually malformed. This behaviour does not seem correct to me.
In case you want to use multiple data sources (input1.yaml
, input2.yaml
), it's best to merge them. In most cases, simple cat input1.yaml input2.yaml >> input_merged.yaml
will work just fine.
You can also pump them right into j2cli
:
cat input1.yaml input2.yaml | j2cli --format=yaml template.j2
Kind regards,
Mark
Hey Mark,
I understand. Thanks for the explanation.
How about my first point?
BR Andreas
Hey @akbo , I'm sorry I forgot about # 1 :)
This actually is Jinja2 behavior: it can ignore undefined top-level variables, but can't ignore accessing missing keys.
Alright, thanks for looking into it.
For my specific use case I found the following workaround (might be interesting for other people having the same issue I have): Jinja2 ignores everything between {% raw %}
and {% endraw %}
. So we can put this around everything that we need to stay as is in the template.