from django.template import Context
from django.template.loader import get_template
from _base import BaseExporter


class HTMLExporter(BaseExporter):
    file_extension = 'html'
    content_type = 'text/html'
    preferred_formats = ('html', 'string')

    def write(self, iterable, buff=None, template=None):
        buff = self.get_file_obj(buff)
        generator = self.read(iterable)

        if template:
            context = Context({'rows': generator})
            if isinstance(template, basestring):
                template = get_template(template)
            buff.write(template.render(context))
        else:
            for row in generator:
                for item in row:
                    buff.write(item)
        return buff
