I want to do this:
<table>
<tr>
{% for image in Images %}
<td><a href="/gallery/image/{{image.id}}/"><img src="{% thumbnail
image.image 200x100 %}"/></a><br/>
{{ image.name }}<br/>
{{ image.comment }}<br/>
</td>
{% if forloop.counter % 4 %}
</tr>
<tr>
{% endif %}
{% endfor %}
</tr>
</table>
which should hopefully give me a gallery of images where each line has four
thumbnails on it.
Unfortunately, I can't do the mod (%) in the if statement, as it's not valid
syntax. Is there a way around this, or a simpler solution?
Thanks,
Tim.
The first thing to do is to step back and remember that the Django
template language is not Python; completely forgetting Python syntax
is a good first step to writing effective templates, because making
assumptions that some bit of syntax will or won't work will get you in
trouble.
The second thing to do is to read the template documentation to see
what is available, because doing so will turn up things like this:
http://www.djangoproject.com/documentation/templates/#divisibleby
--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."
I know that - writing it as python code was the quickest way to get across
what I wanted! :-)
> The second thing to do is to read the template documentation to see
> what is available, because doing so will turn up things like this:
>
> http://www.djangoproject.com/documentation/templates/#divisibleby
I saw that, but I couldn't work out how to conditionally output html based on
its value. {% if forloop.counter|divisibleby: "4" %} doesn't work.
On Monday 24 Mar 2008, Michael Wieher wrote:
> Can you simulate it with an incremental variable?
Sorry, I don't know what you mean. Can you explain more or give me a quick
example?
Thanks,
Tim.
If that's your literal code, you should probably remove the space
between the colon and quote: divisibleby:"4"
What about just converting it to a 2-dimensional array in the view?
For example, using grouper() from the itertools recipes [1]:
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'),
('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
Images = grouper(4, Images)
Then, the logic in the template is straightforward:
<table>
{% for row in Images %}
<tr>
{% for image in row %}
<td>{% if image %} ... image detail ... {% endif %}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
scott.
A-ha, sorted thanks. It wasn't obvious from the documentation that I read
that you could actually use the filters inside {% %} blocks. I know better
now!
Thanks again everyone,
Tim.