Search code examples
flaskjinja2bootstrap-modal

Call a modal (Bootstrap 5) from Jinja2 templating


I'm likely the nth person to have asked this question but am having trouble parsing the relevant documentation; I want to add a modal dialogue to a button declared with a function in Jinja2.

The code for the form where I want the modal to be called is below - the modal should be called when the shutdown button (last line) is pressed, to confirm this action.

 <form class="form form-horizontal" method="post" role="form" 
 style="text-align: center;">
    {{ power_form.hidden_tag() }}
                
    {% if power_status == "None" %}
       {{ power_form.power_on(class_="btn btn-default") }}
       {{ power_form.power_cycle(class_="btn btn-default") }}
       {{ power_form.power_off(class_="btn btn-default") }}

The modal dialogue is called 'Shutdown Confirmation' and has been declared later. I am unsure how to call it as online examples show the button declaration is used instead of the {{. Here is the bootstrap documentation for this:

<button type="button" class="btn btn-primary" data-bs- 
toggle="modal" data-bs-target="#exampleModal">
   Launch demo modal
</button>

Solution

  • With Bootstrap 5 you can activate the modal panel by data attributes or JS API. I assume you want to use the data-attribute method.

    With WTForms you can pass any attribute to the rendered element, just replace any dash with underscore (because Python syntax), and WTForms will change them back to dashes:

    {{ power_form.power_off(type="button", class_="btn btn-default", data_bs_toggle="modal" data_bs_target="#exampleModal") }}
    

    Change the #exampleModal to the corresponding selector of your modal element. We also change the type of the button from the default submit to simple button, so it wont submit the form, just open the modal window.