Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created April 26, 2012 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericmoritz/2502190 to your computer and use it in GitHub Desktop.
Save ericmoritz/2502190 to your computer and use it in GitHub Desktop.
Django chunk filter
from django.template import Library
register = Library()
def chunk(l, n):
return (l[i:i+n] for i in range(0, len(l), n))
register.filter("chunk", chunk)
<div id="empty">{% for chunk in empty|chunk:4 %}
<ul>{% for item in chunk %}
<li>{{ item }}</li>{% endfor %}
</ul>{% endfor %}
</div>
<div id="even">{% for chunk in even|chunk:4 %}
<ul>{% for item in chunk %}
<li>{{ item }}</li>{% endfor %}
</ul>{% endfor %}
</div>
<div id="uneven">{% for chunk in uneven|chunk:4 %}
<ul>{% for item in chunk %}
<li>{{ item }}</li>{% endfor %}
</ul>{% endfor %}
</div>
<div id="empty">
</div>
<div id="even">
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</div>
<div id="uneven">
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
<ul>
<li>8</li>
<li>9</li>
</ul>
</div>
# hack the built-in libs for the demostration, use {% load chunk %}
# when you actually put it in your app's templatetags module
from django.template.base import add_to_builtins
add_to_builtins("chunk")
from django.template import Template, Context
t = Template(open("./usage.html").read())
c = Context({"empty": [],
"uneven": range(10),
"even": range(8)})
print t.render(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment