0

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']

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 %}

2 Comments

I want variable (parameter) as it is in my template file. I am able to get the value of key1 and key2 by using {{key1}} {key2}} in my template file but I want a single variable that contains all the values (value of key1 + value of key2) that I had assigned in variable(parameter).
Thanks ....But I know about the way you mentioned above like making a dictionary and pass all the values at one of key of the dictionary. I want only one dictionary to be passed in the function with many key and values and I can get all of them in a single variable in my template file. I don't know wheather it is possible or not ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.