Template tag for displaying a list of arbitrary models. Useful for life-stream kind of pages that display blog entries, links, photos etc ordered by date. Example
Usage: something like:
{% for object in object_list %}
{% display_excerpt object %}
{% endfor %}
Will look for app/model_excerpt.html by default, and fall back on a generic display_excerpt.html, or returns the object's string representation as a last fallback.
display_excerpt.html might look something like:
<a href="{{ object.get_absolute_url }}">{{ object }}</a>
Any model you throw at it should have a get_absolute_url and a string representation of some sort, so this gives you the bare minimum of a title and a link to a detail page.
display_excerpt takes an optional argument to set the template suffix. This might be handy for generating different formatting for feeds, for instance:
{% for object in object_list %}
{% display_excerpt object "feed" %}
{% endfor %}
This will look for app/model_feed.html to render the object.
Got lots of help from mattmcc on #django for this one, thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django import template
def display_excerpt(object, template_suffix='excerpt'):
excerpt = object._meta.app_label + "/" + object._meta.module_name + "_" + template_suffix + ".html"
try:
t = template.loader.select_template([excerpt, 'display_excerpt.html'])
except template.TemplateDoesNotExist:
return str(object)
c = template.Context({"object": object})
return t.render(c)
register = template.Library()
register.simple_tag(display_excerpt)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.