'How to reference a variable from outside it's loop scope in Django template

I am sorry if the title is poorly phrased, but what i am trying to do is to use a variable that was in a for loop outside of it's scope ( in another part of the template )

here is my template:

<div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
            <label for="{{category.name}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'></div>
    
</div>    

<script>
    $('.category-checkbox input[type="checkbox"]').click(function() {
        if ($(this).is(':checked')) {
          // Add the element to the div with an id identifier
          $('.items').append(`<div id="item_${this.id}">123</div>`);
        } else {
          // Remove the element from the div targeted by the id identifier
          $(`#item_${this.id}`).remove();
        }
      });
</script>

the view.py

def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item}
    return render(request,'inventory.html',context)

i want to be able to use that category variable so i can loop through all the items in that specific category and add them in the items <div>, if there is a better way to do this please guide me !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source