How to access list using variable indexes in Django templates?

前端 未结 2 437
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 01:55

Say, I have two lists of objects, foo and bar. In a Django template, while looping through foo, there\'s a counter that keeps track of

2条回答
  •  青春惊慌失措
    2020-12-11 02:42

    Right, you can't resolve variable names. Definitely try very hard to put this logic in the view.

    But 5% of the time, I do find this extremely limiting at times requiring too much logic in the view / changes required outside the template authors control. I've come to accept a few personal customizations, allowing for variable assignment within the view as well as simple variable resolution.

    It's quite simple to build a template tag that does so though, using the template engines "all lookups in one" system (index, attribute, key).

    from django.template import Variable, VariableDoesNotExist
    
    @register.assignment_tag()
    def resolve(lookup, target):
        try:
            return Variable(lookup).resolve(target)
        except VariableDoesNotExist:
            return None
    
    {% resolve some_list some_index as value %}
    {% resolve some_dict some_dict_key as value %}
    

提交回复
热议问题