Login

Display arbitrary models

Author:
bjornkri
Posted:
July 17, 2008
Language:
Python
Version:
.96
Tags:
display excerpt lifestream
Score:
0 (after 0 ratings)

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

  1. Pagination/Filtering Alphabetically by zain 5 years, 12 months ago
  2. Class Feeds DRY TemplateTag by gmandx 4 years, 9 months ago
  3. Page numbers with ... like in Digg by Ciantic 5 years, 10 months ago
  4. Pagination Alphabetically compatible with paginator_class by vascop 2 years, 10 months ago
  5. Digg-like pagination by SmileyChris 5 years, 9 months ago

Comments

Please login first before commenting.