orph-c
orph-c

Reputation: 73

How to set the id of an HTML element with Django variable?

Right now, I'm displaying a bunch of elements using data from a Python dictionary, which looks something like {"id", "content", "id2": "content2"}. I'm then passing that to an HTML template through Django, and running a for loop to create an element for every item in the dictionary. The problem is, I'm going to add other front-end features via javascript, that require each element created to have a unique id in HTML, which I want to be set to the key of the python dictionary (So the first element has id of 'id', second element has an id of 'id2'...)

So, how do I set the id of the element to be the Django variable? I know it isn't the for loop's problem, since I can print out the id variable just fine.

Python code

objects = {"A1": "xxx", "B2": "yyy", "C3": "zzz"}
return render(request, "website/index.html", {
        "objects": objects
})

index.html

{% for object, specs in objects.items %}
       <div class="status">
            Chunk of irrelevant code here 
       </div>
{% endfor %}

I want each div with class status to also have an id of "A1" or "B2" and so on, but I don't know how to assign this

Upvotes: 0

Views: 2801

Answers (1)

Aman Garg
Aman Garg

Reputation: 2547

You can use template variables anywhere in your template using {{ and }}.

{% for object, specs in objects.items %}
       <div class="status" id="{{ object }}">
            Chunk of irrelevant code here 
       </div>
{% endfor %}

Upvotes: 4

Related Questions