Accessing a dict by variable in Django templates?

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

    <tr>
    <!-- iterate columns in order specified -->
    {% for key in columns %}
    <th>
     <span class="column-title">
        <!-- look label in meta dict.  If not found, use the column key -->
       {{columnMeta|getitem:key|getitem:"label"|default:key}}
      </span>
    </th>
    {% endfor %}</tr>
    
    0 讨论(0)
  • 2020-12-09 09:00

    Try this to display the keys and values of the dictionary:

    {% for key, value in your_dict.items %}
        {{ key }}: {{ value }}
    {% endfor %}
    

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-09 09:13

    There's no builtin way to do that, you'd need to write a simple template filter to do this: http://code.djangoproject.com/ticket/3371

    0 讨论(0)
提交回复
热议问题