Ujjwal Joshi
Ujjwal Joshi

Reputation: 1

Python - Get all the variable in template passed from views.py render() function

Code in my views.py


from django.shortcuts import render
def webapppage(request):
    parameter = {
    'key1':'hello',
    'key2':['hiiii','whats up','buddy']
    }
    return render(request, 'template2.html', parameter)

How can I get both {{key1}} and {{key2}} in one single variable like (parameter) in my template file?

Code inside template2.html


{% for c in parameter %}
    `{{c}}
{% endfor %}

I want output like


hello ['hiiii','whats up','buddy']

Upvotes: 0

Views: 762

Answers (2)

xeqthor
xeqthor

Reputation: 1

If you want that output just replace your template with:

{{parameter.key1}} {{parameter.key2}}

If you want to keep your template as it is then pass the context as a list like:

return render(request, 'questapp/template2.html', {'parameter': [v for v in 
               parameter.values()]})

If you want to pass a dictionary then you can try:

return render(request, 'questapp/template2.html', {'parameter': 
                                                  parameter})

and change your template:

{% for  c in parameter.values %}
    {{c}}
 {% endfor %}

Upvotes: 0

LearnerAndLearn
LearnerAndLearn

Reputation: 393

As I read your requirement, you want to pass one dictionary with many key and values. We might do something like this.

In views.py

def webapppage(request):
    parameter = {
        'key1':'hello',
        'key2':['hiiii','whats up','buddy']
    }

    context = {
        "parameter" : parameter 
    } # The template will only contain one dictionary

    return render(request, 'template2.html', context=context)

In the template

{% for key, value in parameter.items %}
    {% if key == 'key1' %}
        {{ value }}
    {% else %}
        {% for name in value %}
            {{ name }}
        {% endfor %}
    {% endif %}
{% endfor %}

Now the template will able to get all value in a single variable.

Upvotes: 0

Related Questions