Go through the dictionary in the template

4

I have the following view:

from django.shortcuts import render

def ini (request):
    dic = {"nombre" : "Mauro", "apellido" : "London", "sexo" : "M"}
    return render(request, "ini.html", dic )

and the ini.html:

{% extends 'base.html' %}
{% block content %}
 <body>
 <h1>Esto es una prueba {{ nombre }} {{ apellido }}</h1>
 <ul>
    {% for valor in dic %}
      <li>{{ dic[valor] }}</li>
    {% endfor %}
 </ul>
</body>
{% endblock %}

My question: I see that both the dictionary key "name" and "surname" are printed if I refer directly to it ... but I do not know how to print the dictionary by going through a for. I do it as it is done in python but I get an error.

I've tried with:

{% extends 'base.html' %}
{% block content %}
 <body>
 <h1>Esto es una prueba {{ nombre }} {{ apellido }}</h1>
 <ul>
    {% for key, value in dic.items %}
      <li>{{ key }} : {{ value }}</li>
    {% endfor %}
 </ul>
</body>
{% endblock %}

does not give an error but does not print anything ....

    
asked by Mauro 11.10.2018 в 01:56
source

1 answer

5

The dictionary keys that you pass to the argument context of render in the view are the variables that you can use in the template. In other words, when you do {% for key, value in dic.items %} it's as if you were searching for the key "dic" in the dictionary dic passed to render .

What you can do is simply pass your dictionary as a value of a dictionary key:

view.py

from django.shortcuts import render

def ini(request):
    dic = {"nombre" : "Mauro", "apellido" : "London", "sexo" : "M"}
    return render(request, 'ini.html', context={"dic": dic})

ini.html

{% extends 'base.html' %}
{% block content %}
<body>
    <h1>Esto es una prueba {{ dic.nombre }} {{ dic.apellido }}</h1>
    <ul>
        {% for key, value in dic.items %}
        <li>{{ key }} : {{ value }}</li>
        {% endfor %}
    </ul>
</body>
{% endblock %}

With this you must obtain what you are looking for:

  

This is a Mauro London test

  • name: Mauro
  •   
  • surname: London
  • sex: M
answered by 11.10.2018 / 07:30
source