Accessing a dict by variable in Django templates?

前端 未结 4 1095
忘掉有多难
忘掉有多难 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 08:54

    Here's a usage case of the suggested answer.

    In this example, I created a generic template for outputting tabular data from a view. Meta data about the columns is held in context["columnMeta"].

    Since this is a dictionary, i cannot rely on the keys to output the columns in order, so i have the keys in a separate list for this.

    In my view.py:

    
    c["columns"] = ["full_name","age"]
    c["columnMeta"] = {"age":{},"full_name":{"label":"name"}}
    

    In my templatetags file:

    
    @register.filter
    def getitem ( item, string ):
      return item.get(string,'')
    

    In my template:

    
    
    {% for key in columns %}
    
     
        
       {{columnMeta|getitem:key|getitem:"label"|default:key}}
      
    
    {% endfor %}
    

提交回复
热议问题