Home > OS >  Loop through Django context values
Loop through Django context values

Time:06-09

How do I render a context value as a key-value list in template?

def random_view(request):
   my_context = {
       "name": "turkey",
       "fly": "no",
       "run": 20
   }
   return render(request, 'test/test.html', my_context)

If this is the views the views then how can I loop through the values and render a list in test.html using a loop?

CodePudding user response:

Pass it as a single variable:

def random_view(request):
    my_context = {
        'data': {
            'name': 'turkey',
            'fly': 'no',
            'run': 20
        }
    }
    return render(request, 'test/test.html', my_context)

Then in the template, you can loop over the data variable:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}
  • Related