简体   繁体   中英

Load several templates into a base template in django on buttonclick

I have several apps (app1.html, app2.html etc.) and a base.html that has (let's say) 4 placeholders. Now I want to enable the user by clicking on one of the placeholders to choose from these apps and load them into that placeholder. Here's a simple example with js for more clarity: https://jsfiddle.net/eja4t0gb/15/

HTML:

  <body>
    <div id="module-1" class="">
      This is module 1.
      <button id="load-1">Load Module</button>
    </div>
    ---
    <div id="module-2" class="">
      This is module 2.
      <button id="load-2">Load Module</button>
    </div>
    ---
    <div id="module-3" class="">
      This is module 3.
      <button id="load-3">Load Module</button>
    </div>
    ---
    <div id="module-4" class="">
      This is module 4.
      <button id="load-4">Load Module</button>
    </div>
    --- ---
    <div id="chooser">
      Choose an App.
      <button id="app-1">App-1</button>
      <button id="app-2">App-2</button>
      <button id="app-3">App-3</button>
      <button id="app-4">App-4</button>
    </div>
  </body>
</html>

Javascript:

var chosenModule = null;
document.getElementById("chooser").style.display = "none";

for (let i = 1; i <= 4; i++) {
  document.getElementById("load-" + i).addEventListener("click",
    function() {
      chosenModule = i;
      document.getElementById("chooser").style.display = "block";
    });
}

for (let i = 1; i <= 4; i++) {
  document.getElementById("app-" + i).addEventListener("click",
    function() {
      loadApp(i);
      document.getElementById("chooser").style.display = "none";
      document.getElementById("app-" + i).style.display = "none";
    });
}

function loadApp(i) {
  document.getElementById('module-' + chosenModule).innerHTML = "App" + i;
}

Here's my question: How would I implement this with django templates/Jinja2?

Now I have seen this post: Django: Loading another template on click of a button , however, there the goal was to load a completely new page. I on the other hand want to additionally load the apps with all their resources only after the button click, without having to reload the page itself. I know about {% include 'app.html' %}, but how can I tell the base.html to only interpret this after the click of a button/via js code? Or is is 'include' the wrong approach here?

Actually, Django templates work on HTTP protocol which is stateless . It mean you can not get other template once you have rendered it!But, you can use ajax request to fetch django template from your webapp.

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