1

I am attempting to build a Django template that dynamically handles variables that may or may not exist.

Here is the type of pattern I am using:

{%  block unsubscribe %}
        {%  if unsubscribe_uuid is not None %}
            <a href="http://www.example.com/core/unsubscribe/{{ unsubscribe_uuid }}/" style="
                font-size: .9em;
                color: rgba(255, 255, 255, 0.5);">
                unsubscribe</a> |
        {%  endif %}
    {% endblock %}

This throws an error/exception/warning:

django.template.base.VariableDoesNotExist: Failed lookup for key [unsubscribe_uuid]

I've also tried checking with this line to check for the variable:

{%  if unsubscribe_uuid %}

How can I check for variables in my template without throwing this error if they don't exists?

Lee Loftiss
  • 3,035
  • 7
  • 45
  • 73
  • `{% if unsubscribe_uuid %}` `{% end if %}` seems like the right way, interesting situation, never seen this before. Just maybe this one can somehow help? https://stackoverflow.com/questions/35787497/variabledoesnotexist-failed-lookup-for-key-val2-in-unone – Adil Shirinov Sep 01 '20 at 12:23
  • @AdilShirinov Thanks. I didn't find that page in my search. Their solution didn't work. And they had a link that explains it is a know issue and there is no intention to fix it due to more issues being caused by the solution. https://code.djangoproject.com/ticket/28172 – Lee Loftiss Sep 01 '20 at 12:31

1 Answers1

0

I suggest doing something like this:

{%  block unsubscribe %}
  {% with unsubscribe_uuid as uuid %}
     {%  if uuid is not None %}
       <a href="http://www.example.com/core/unsubscribe/{{uuid}}/" style="font-size: .9em;color: rgba(255, 255, 255, 0.5);">unsubscribe</a> |
     {%  endif %}
 {% endwith %}
{% endblock %}
Riyas Ac
  • 1,553
  • 1
  • 9
  • 23
  • Thanks for the suggestion. Unfortunately it didn't prevent the warning. Maybe it is my approach. Any idea if this is the best way to attempt loading sub-templates only when needed? – Lee Loftiss Sep 01 '20 at 18:22