Creating a list on the fly in a Django template

后端 未结 2 521
梦毁少年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条回答
  •  猫巷女王i
    2020-12-08 18:25

    If you want to add a new variable (ie some_list), you'll need access to the template's context, so simple_tag won't be enough.

    For me, the first approach is to try to do this sort of work in the view, in order to keep the templates as simple as possible.

    If that's not appropriate, you'll have to write the tag manually, like this:

    @register.tag
    def make_list(parser, token):
      bits = list(token.split_contents())
      if len(bits) >= 4 and bits[-2] == "as":
        varname = bits[-1]
        items = bits[1:-2]
        return MakeListNode(items, varname)
      else:
        raise template.TemplateSyntaxError("%r expected format is 'item [item ...] as varname'" % bits[0])
    
    class MakeListNode(template.Node):
      def __init__(self, items, varname):
        self.items = map(template.Variable, items)
        self.varname = varname
    
      def render(self, context):
        context[self.varname] = [ i.resolve(context) for i in self.items ]
        return ""
    

    And use it like this to create a new variable some_list:

    {% make_list var1 var2 var3 as some_list %}
    

    Feel free to give it a better name!

提交回复
热议问题