简体   繁体   中英

How to call a modal from a different HTML File

I realise there are similar questions on stackoverflow, however they either seem outdated(bootstrap3) or are not working for me. If possible I want to just stick to html css and javascript. I would prefer not using jquery or php.

I'll keep my code very general. I have my mainscreen which has a button I need that button to call a modal from ModalPage . ModalPage only has that modal with no other code. I'm using flask-python as my backend.

Mainscreen

<button type="button" class="btn btn-primary btn-lg">This should call modal/button>

ModalPage

<div class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

I have tried using url_for and rendering it using <a> but that doesn't seem to be working

You might have to store the entire modal HTML in a variable within your Python Flask code. One way (out of quite a few number of ways) would be to read the text and store the html in a variable using:

modaltext=[]
with open('ModalPage.html', 'r') as f:
    content = f.read()
    modaltext.append(content)

Put this above code in your views.py preferably. That filename depends on where you have stored the ModalPage.html. Here I assumed, it is in the same folder as views.py (which might not be the case. It could be in templates, but I dunno your folder structure).

And modify your return render statement to also return the modaltext list.

Then, call it to your Mainpage HTML using jinja2 syntax wherever necessary. Typically it could be like:

<div>{{ modal }}</div>

I'm honestly not sure about the python/flask portion, but I do what you are attempting using only html/js. You could add an ID to the button, ie 'modal-form-button'. Then make an event listener in JS for the element with that ID being clicked.

document.getElementById("test-btn").addEventListener("click", showModal);

The showModal() function can contain the necessary code to toggle the display of the modal between 'display:bloack' and 'display:none'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM