Accessing a dict by variable in Django templates?

前端 未结 4 1087
忘掉有多难
忘掉有多难 2020-12-09 08:31

My view code looks basically like this:

context = Context() 
context[\'my_dict\'] = {\'a\': 4, \'b\': 8, \'c\': 15, \'d\': 16, \'e\': 23, \'f\': 42 }
context         


        
4条回答
  •  鱼传尺愫
    2020-12-09 09:09

    For my needs, I wanted a single template filter that would work for dicts, lists, and tuples. So, here's what I use:

    @register.filter
    def get_item(container, key):
        if type(container) is dict:
            return container.get(key)
        elif type(container) in (list, tuple):
            return container[key] if len(container) > key else None
        return None
    

提交回复
热议问题