Search code examples
javascriptflaskhandlebars.js

Dynamically render template without reloading page


Just started making a Flask app to make a simple Wizard. For now I have just two "Steps", each with its own HTML templated file; Jinja is the templating language. The first pass at this makes it so that on "Next" and "Previous" it routes to a new page.

Simple enough but now I want to convert this into a one-page app. Using Handlebars it was as simple as having a main container div, then rendering separate templates when clicking next/previous buttons.

Is there a way to do this in Flask? A way to use JS or Flask to render or load a template HTML file to a div container?


Solution

  • You can use AJAX to load content from the server without reloading the whole page.

    As an example:

    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <script>
      $(document).ready( function() {
            $('#next').click(function() {
               $.ajax("{{ url_for('myroute') }}").done(function (reply) {
                  $('#container').html(reply);
               });
            });
      });
    </script>
    
    <input type="button" id="next" value="Next" />
    <div id="container"></div>