Creating a list on the fly in a Django template

后端 未结 2 517
梦毁少年i
梦毁少年i 2020-12-08 17:43

I don\'t know whether it\'s possible, but I\'d like to be able to write something like the following:

{% with var1 var2 var3 as some_list %}
    {{ some_list         


        
2条回答
  •  隐瞒了意图╮
    2020-12-08 18:21

    I played around a bit and came up with a tag that can accept a variable number of arguments and convert them into a list.

    @register.tag('to_list')
    def to_list(_parser, token):
        try:
            parts = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError, \
              "%r tag requires at least one argument" % token.contents.split()[0]
    
        return AsListNode(parts[1:])
    
    class AsListNode(template.Node):
        def __init__(self, parts):
            self.parts = map(lambda p: template.Variable(p), parts)
    
        def render(self, context):
            resolved = []
            for each in self.parts:
                resolved.append(each.resolve(context))
            return resolved
    

    Template:

    {% to_list var1 var2 var3 %}

    Update

    @Will's solution is better. It lets you save the resulting list using another variable so that you can operate on it later.

提交回复
热议问题