Generate elements dynamically in a template in Django

1
{%for i in cont%}
        <p>{{"module"+i}}</p>
{%endfor%}

I have this code in my template, and what I want is that it takes for each iteration of the for, a value of a dictionary that comes from the views.py whose keys are module1, module2, etc ...

This is the code of my views.py file in which I pass the values to the template:

context = {}
        for module in globals.all_modules:
            context['module' + str(cont)] = module
            cont += 1
        context['cont'] = range(1,cont)
        return render(request,'modules.html',context)

With this code it does not show anything, I guess it's because the template does not take the data that comes from views.py if it is with quotes.

    
asked by G3l0 20.04.2017 в 10:50
source

1 answer

1

The solution I found is this one.

The part of the views.py looks like this:

context = {'modules' : {}}
for module in globals.all_modules:
    context['modules'][module] = "module" + str(cont)
    cont += 1
return render(request,'modules.html',context)

And the part of the template like this:

{%for module in modules%}
    <p>{{module}}</p>
{%endfor%}
    
answered by 21.04.2017 / 08:33
source