Oct 31

Satchmo product images

Templatetag for Satchmo creates unordered list for product images. CSS can be applied to customize output.

from django import template

from satchmo.product.models import Product
from satchmo.thumbnail.templatetags.satchmo_thumbnail import thumbnail

    from xml.etree.ElementTree import Element, SubElement, tostring
except ImportError:
    from elementtree.ElementTree import Element, SubElement, tostring

register = template.Library()

default_opts = {
    'thumbnail': 'width=280',
    'start': 0

class ProductGalleryNode(template.Node):
    def __init__(self, product, **opts):
        self.product = template.Variable(product)
        self.opts = default_opts

    def render(self, context):
        actual_product = self.product.resolve(context)
        images = actual_product.productimage_set.all()
        start = int(self.opts['start'])
        if len(images) <= start: return ("")
        root = Element("ul", {'class': self.opts.get('class', '')})
        for (i, pic) in enumerate(images[start:]):
            li_attr = {'class': 'first'} if not i else {}
            li = SubElement(root, 'li', li_attr)
            link = SubElement(li, 'a', {'href' : pic.picture.url})
            caption = pic.translated_caption()
            src = thumbnail(pic.picture.url, self.opts.get('thumbnail'))
            img = SubElement(link, 'img', {'src': src, 'alt': caption, 'title': caption})
        return tostring(root, 'utf-8')        

def product_gallery(parser, token):
    """ Returns an unordered list of image thumbnails for product.

{% product_gallery product %}
{% product_gallery product thumbnail="width=280"%}
{% product_gallery product start=1%}
{% product_gallery product class=galeria%}

    kwargs = {}
    bits = token.split_contents()[1:]
    product = bits[0]
    for bit in bits[1:]:
        arg, val = bit.split("=", 1)
        kwargs[str(arg)] = val.strip('"')
    return (ProductGalleryNode(product, **kwargs))