Reputation: 4008
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'
Upvotes: 1
Views: 121
Reputation: 8525
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 %}
Upvotes: 1
Reputation: 942
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
Upvotes: 1