Forums

Display output from .py file withing HTML content

For my site I have this .py file:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    output = "Hello, Maria!"
    return render_template('index.html', output=output)

if __name__ == '__main__':
    app.run()

And this HTML file:

 <!DOCTYPE html>
<html>
<head>
  <title>My Flask App</title>
</head>
<body>
  <h1>Welcome to My Flask App</h1>
  <div id="output"></div>
</body>
</html>

My goal is to get "output" displayed on my website, but it's not being displayed.

What am I doing wrong?

I also tried it with this code, and get the same result:

from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/get_output', methods=['GET'])
def get_output():
    output = "Hello, Flask!"
    return jsonify(output=output)

if __name__ == '__main__':
    app.run()

And HTML:

<!DOCTYPE html>
<html>
<head>
  <title>My Flask App</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
  <h1>Welcome to My Flask App</h1>
  <div id="output"></div>

  <script>
    $(document).ready(function() {
      // Make an AJAX request to your Flask route to get the dynamic content
      $.ajax({
        url: '/get_output',
        method: 'GET',
        success: function(response) {
          // Update the content of the 'output' div with the response
          $('#output').html(response);
        }
      });
    });
  </script>
</body>
</html>

In your first example, you need to tell the template where to insert the value you're putting into the output variable. So, for example, you could replace

<div id="output"></div>

...with this:

<div id="output">{{ output }}</div>

The name of your div is not something that the template processor would pay any attention to; it only replaces things that are expressed in the Jinja templating language's syntax.

In the second example, you're passing an object rather than a string into the html method, and I don't know what JavaScript would do with that -- perhaps it would ignore it. You should pass in the string in the output field instead, ie.

$('#output').html(response.output)

Both of those worked.

Thank you!

And I appreciate you taking the time to answer a dumb newbie question.

Glad we could help!