0

In Django templates we can use with:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

Can we use with in combination with if

I tried:

{% with a={%if product.url %}product.url{%else%}default{%endif %} %}

but I get an error:

Could not parse the remainder: '{%if' from '{%if'
user3541631
  • 3,686
  • 8
  • 48
  • 115
  • Possible duplicate of [Django template conditional variable assignment](https://stackoverflow.com/questions/10786214/django-template-conditional-variable-assignment) – jonrsharpe May 20 '18 at 09:27

2 Answers2

1

At least Django template language is quite silly - the logic should not take place in the template - so think about a template tag => register your own and try to move the logic in the view...

In this case the question might be why you're trying to do this?

Probably it might be easier to use the variable directly where you need to and in case it is None use the default template tag / function:

{{ product.url|default_if_none:default }}

But anyway your solution might look like:

{% with a=default %}
  {% if product.url %}
    {% update_variable product.url as a %}
  {% endif %}
{% endwith %}

And your template tag should look like:

@register.simple_tag
def update_variable(value):
    return value
nrhode
  • 913
  • 1
  • 9
  • 27
  • I have two fields/columns in the database, if a field is empty I get the value from the other field; because is obtained as a more complex queryset(with multiple prefetch_related) I don't do the logic in the View – user3541631 May 20 '18 at 09:53
  • hmm ok - than do it with the template tag I posted - should work anyway... – nrhode May 20 '18 at 09:55
1

A tag filter that might work:

from django import template

register = template.Library()

@register.simple_tag
def fallback(value, default_value):
     if not value:
         return default_value
     return value

In templates, you need to load the files

{% load app_containing_tag_filters %}

{% with a = product.url|fallback:default %}
     stuffs here
{% endwith %}
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50