0

I'm using Jinja2 to create email notification messages, mostly error notifications.

Sometimes I get invalid or incomplete data about the error details. After all, it is an error condition when this happens. E.g. a dict item might be missing or value type could be incorrect. In such case the rendering fails, but the error notification has to be sent.

I can do following in the exception handler:

  1. To send the template as-is. At least the type of error event will be known to the recipient, but important data will be missing
  2. To send a backup template with just raw data. That would mean to maintain two versions of each message.

What I really want is to render the template on a "best-effort" basis skipping all errors. Is there a way to do that in Jinja2?

VPfB
  • 14,927
  • 6
  • 41
  • 75

1 Answers1

0

Use defaults everywhere it's necessary. Also handles undefined variables:

default(value, default_value=u'', boolean=False):

If the value is undefined it will return the passed default value, otherwise the value of the variable:

{{ my_variable|default('my_variable is not defined') }}

This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not defined'. If you want to use default with variables that evaluate to false you have to set the second parameter to true:

{{ ''|default('the string was empty', true) }}

Or you could use none if you're creating more complex structures based on the data:

{% if p is not none %}   
    {{ p.User['first_name'] }}
{% else %}
    NONE
{%endif %}
Community
  • 1
  • 1
aneroid
  • 12,983
  • 3
  • 36
  • 66
  • I'm afraid this does not protect from errors like applying number or date/time formatting to None value etc. As I wrote I must accept inconsistent source data and I cannot predict all possible problems within that data. – VPfB May 07 '17 at 09:31
  • Then I recommend using only safe values in your template followed by a stringification of everything else. Not ideal but at least you get the info in your email. Why not try putting the error handling in your code before jinja processes it? – aneroid May 07 '17 at 13:04
  • 1
    Thank you for your suggestions. The notification system is just one of several modules in a larger system communicating via RPC. I want to make it more robust and simple `"N/A"` on place of each Jinja's failed `{{ expression }}` would be all I need. Such functionality seems to be not available - and that is also an answer to my question. – VPfB May 07 '17 at 14:47