如何在 Django 模板中从其循环范围之外引用变量

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

如果标题措辞不当,我很抱歉,但我想做的是使用 for 循环中超出其范围(在模板的另一部分)的变量

这是我的模板:

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

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)

我希望能够使用该类别变量,以便我可以遍历该特定类别中的所有项目并将它们添加到项目中 <div>,如果有更好的方法,请指导我!

click 替换为 on 事件,因为您正在动态添加这样的元素:

$('.category-checkbox input[type="checkbox"]').on('click', function() {
    // rest of your code
});