Created
April 26, 2012 19:16
-
-
Save ericmoritz/2502190 to your computer and use it in GitHub Desktop.
Django chunk filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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