Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to a Bootstrap modal in jinja template (one of them from inside a for loop)

I have a jinja template with 2 variables (one of them inside a for loop) and I want to pass them to a bootstrap modal in order to confirm a delete that is triggered within the loop. The schema of it is something like this:

<object_outside_loop>
<!-- Loop -->
{% for item_inside_loop in items %}
    <button type="button" data-toggle="modal">Delete</button>
{% endfor %}

<!-- Modal -->
<my-modal-here>
    <a href="{{ url_for('delete_something', id1=object_outside_loop._id, id2=item_inside_loop._id) }}" >Confirm Delete</a>
</my-modal-here>

and I need to pass both variables (id1 and id2) from the modal to my route:

@app.route("/delete_something/<id1>/<id2>")
def delete_something(id1, id2):

    mongo.db.something.update_one(
        {"_id": ObjectId(id2)},
        {"$pull": {"something": {"_id": ObjectId(id1)}}},
    )
    flash("Your something has been updated!", "success")
    return redirect(url_for("somewhere", id=id2))

How can I pass those two variables to the modal, and how do I do that without breaking the endpoint?

like image 509
Guillermo Brachetta Avatar asked Oct 15 '25 07:10

Guillermo Brachetta


1 Answers

Please try the below...

Asumption: id of your modal is my-modal

Change how you are displaying the Delete button:

{% for item_inside_loop in items %}
    <button type="button" data-toggle="modal" data-target="#myModal" data-url="{{url_for('delete_something', id1=object_outside_loop._id, id2=item_inside_loop._id)}}">Delete</button>
{% endfor %}

Change the Delete button, which in modal to:

<a id="confirm-delete">Confirm Delete</a>

Now, on click of Delete button in modal, change it to:

$(document).ready(function(){
    $("#my-modal").on("show.bs.modal", function(event){
        // Get the button that triggered the modal
        var button = $(event.relatedTarget);

        // Extract value from the custom data-* attribute
        var url = button.data("url");
        $(this).find('#confirm-delete').attr('href', url)
    });
});

I hope the above works for you.

like image 58
ngShravil.py Avatar answered Oct 16 '25 20:10

ngShravil.py