On Feb 7, 8:30 am, toomim <[EMAIL PROTECTED]> wrote: > On Feb 6, 11:05 pm, toomim <[EMAIL PROTECTED]> wrote: > > > I don't understand, how do I get {{sep}} to change from ',' to 'and' > > and then to the empty string in the last 2 iterations of the loop, > > without using a bunch of if statements? (And since we're using > > variables, a {% where %} clause?)
You could write a custom tag... The code below needs to be put in a file called dktags.py (or you need to change the {% load dktags %} line), in a directory named templatetags in the same directory that contains your model.py and views.py files. The templatetags directory also needs to contain an empty file named __init__.py The output is John, Paul, Ringo and George There's virtually no error analysis and I can't imagine anything good would happen if you try to use it on a sequence with less than two items... I'm leaving that as an exercise for the reader ;-) enjoy, -- bjorn from django import template register = template.Library() class CommaListNode(template.Node): def __init__(self, var, lst, sepvar, first, last, nodes): self.var = var self.lst = lst self.sepvar = sepvar self.first = first[1:-1] # strip quotes self.last = last[1:-1] self.nodes = nodes def __rendernodes(self, ctx, loopvar, sepvar): ctx[self.var] = loopvar ctx[self.sepvar] = sepvar return self.nodes.render(ctx) def render(self, ctx): res = [] # lookup what we're looping over and convert to a list # so that we can do negative indexing... lst = list(ctx[self.lst]) for item in lst[:-2]: res.append(self.__rendernodes(ctx, item, self.first)) res.append(self.__rendernodes(ctx, lst[-2], self.last)) res.append(self.__rendernodes(ctx, lst[-1], '')) return ''.join(res) @register.tag def commalist(parser, token): try: COMMALIST, var, IN, lst, WITH, sepvar, first, FINALLY, last = token.split_contents() nodes = parser.parse(['endcommalist']) parser.delete_first_token() except: raise templateTemplateSyntaxError("something's wrong") return CommaListNode(var, lst, sepvar, first, last, nodes) if __name__ == "__main__": from django.template import Context, Template from datakortet.tiktok.models import * t = Template(''' {% load dktags %} {% commalist n in names with sep ", " finally " and " %}{{n}} {{sep}}{% endcommalist %} ''') ctx = Context({'names': 'John Paul Ringo George'.split()}) print t.render(ctx) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---