Reputation: 13682
Here is the monster inefficient code:
{% for link in header_links %}
{% if not link.image %}
{% if not link.url %}
<li><a href="{{ link|lower }}">{{ link }}</a></li>
{% else %}
<li><a href="{{ link.url }}">{{ link }}</a></li>
{% endif %}
{% else %}
{% if not link.url %}
<li><a href="{{ link|lower }}"><img src="{{ link }}" /></a></li>
{% else %}
<li><a href="{{ link.url }}"><img src="{{ link.image }}" /></a></li>
{% endif %}
{% endif%}
{% endfor %}
As you can see, this is ridiculous. A simple tertiary statement or two would be totally fitting, except within the {% %} blocks I can't access the variables with filters and things like that.
Here is my python/django pseduo code that expresses the same thing with the efficiency I think is possible.
{% for link in header_links %}
<li><a href="{% print link|lower if not image.url else image.url %}">{% print "<img src='" + link.image + "' />" if link.image else print link %}</a></li>
{% endfor %}
As you can see, using two tertiary statements would be awesome and much more visually efficient anyway. Yet this code doesn't work.
Any suggestions would be awesome!!
Thanks, Django Noob
IN CLOSING:
We came to the conclusion that following the MVC paradigm leads me to do the "heavy" lifting to the controller section and give the view as little thinking as possible.
The pseudo code I will end up using will be as follows:
in the view
header_links = {}
links = Link.object.all()
for link in links:
header_links['url'] = (link.name if not link.url else link.url)
header_links['name'] = (link.name if not link.image else "<img src='" + link.image +"' />")
context = Context({
"header_links": header_links
})
in the controller
{% for link in header_links %}
<li><a href="{{ link['url']|lower }}"><img src="{{ link['name'] }}" /></a></li>
{% endfor %}
Upvotes: 0
Views: 199
Reputation: 11259
How about this?
{% for link in header_links %}
<li>
{% if link.url and link.image %}
<a href="{{ link.url }}"><img src="{{ link.image }}" /></a>
{% elif not link.url %}
<a href="{{ link|lower }}"><img src="{{ link }}" /></a>
{% elif not link.image %}
<a href="{{ link.url }}">{{ link }}</a>
{% else %}
<a href="{{ link|lower }}">{{ link }}</a>
{% endif%}
</li>
{% endfor %}
Upvotes: 1
Reputation: 29804
Just rewrote your if statement and I think this way looks more obvious. Is not the most clever solution but It's more readable.
{% for link in header_links %}
{% if not link.image and not link.url%}
<li><a href="{{ link|lower }}">{{ link }}</a></li>
{% endif %}
{% if not link.image and link.url%}
<li><a href="{{ link.url }}">{{ link }}</a></li>
{% endif %}
{% if link.image and not link.url%}
<li><a href="{{ link|lower }}"><img src="{{ link }}" /></a></li>
{% endif %}
{% if link.image and link.url%}
<li><a href="{{ link.url }}"><img src="{{ link.image }}" /></a></li>
{% endif %}
{% endfor %}
Upvotes: 2