Reputation: 1895
I'd like to list a series of items separated by commas.
But if an item after the first doesnt exist, I don't want the comma or item to appear.
So I've implemented this:
<em>{{object.item1|default_if_none:""}}</em>
{% if object.item2 %}
<em>, {{object.item2|default_if_none:""}},</em>
{% endif %}
<em>{{object.item3|default_if_none:""}}</em>
If object.item2 exists, it'll put a whitespace after item1--before the comma.
When it displays, it'll look something like:
"I_am_item_one , I_am_item_two, Item_three"
What's the best way to fix this?
edit: is it possible to for-loop through an object's properties?
{% for property in object.property %}
or similar..
Upvotes: 0
Views: 188
Reputation: 399
I am not aware of any way to loop over objects and their properties in a template. You could look into either passing the data into the template as a dictionary/list or creating a model method (as done in this answer: Django templates: loop through and print all available properties of an object?)
Once your data is iterable, you could use the following code to decide when to add a comma. I am not entirely clear if you want a comma between each item or only after the first item, so here are two options.
This will only add a comma on the first entry
{% for item in item_list %}
<em>{{ item }}</em>{% if forloop.first %}, {% endif %}
{% endfor}
This will add a comma after each item except the last one
{% for item in item_list %}
<em>{{ item }}</em>{% if not forloop.last%}, {% endif %}
{% endfor}
It is probably fairly clear, but you can use forloop.first
to detect when you are on your first item and forloop.last
to detect when you are on the last item of a loop.
Upvotes: 3