# vim: set fileencoding=utf-8 ts=4 shiftwidth=4 softtabstop=4 expandtab: from django import template from django.template.defaultfilters import stringfilter from oembed.core import replace register = template.Library() class IfIsNewNode(template.Node): def __init__(self, arg1, arg2, nodelist_true, nodelist_false, negate): self.arg1, self.arg2 = arg1, arg2 self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.negate = negate def render(self, context): try: val1 = template.resolve_variable(self.arg1, context) except VariableDoesNotExist: val1 = "" try: val2 = template.resolve_variable(self.arg2, context) except VariableDoesNotExist: val2 = "" if (not self.negate and val1 > val2) or (self.negate and val1 <= val2): return self.nodelist_true.render(context) return self.nodelist_false.render(context) def do_ifisnew(parser, token, negate): "Returns true if message is new" args = token.split_contents() if len(args) != 3: raise template.TemplateSyntaxError("'is_new' needs two arguments.") end_tag = 'end' + args[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = template.NodeList() node = IfIsNewNode(args[1], args[2], nodelist_true, nodelist_false, negate) return node @register.tag def ifisnew(parser, token): return do_ifisnew(parser, token, False) @register.tag def ifisnotnew(parser, token): return do_ifisnew(parser, token, True) @stringfilter def my_oembed(input, args): args = args.split() if len(args) > 1: raise template.TemplateSyntaxError("Oembed tag takes only one (option" \ "al) argument: WIDTHxHEIGHT, where WIDTH and HEIGHT are positive " \ "integers.") if len(args) == 1: width, height = args[0].lower().split('x') if not width and height: raise template.TemplateSyntaxError("Oembed's optional WIDTHxHEIGH" \ "T argument requires WIDTH and HEIGHT to be positive integers.") else: width, height = None, None kwargs = {} if width and height: kwargs['max_width'] = width kwargs['max_height'] = height return replace(input, **kwargs) register.filter('my_oembed', my_oembed)