skip to Main Content

I have been attempting to flash a simple message to a webpage via Flask and Jinja, and yet it always reuslts in the jinja code being displayed as simple text.

Here is my app.py code:

from flask import Flask, flash, redirect, render_template

app = Flask(__name__)
app.config['SECRET_KEY'] = '12345'

@app.route('/')
def index():
    flash('Hello, this is a flash message!')
    return render_template('index.html')

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

Here is my index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flash Message Example</title>
</head>
<body>
    {% for mesg in get_flashed_messages() %}
        <h1>{{ mesg }}</h1>
    {% endfor %}
</body>
</html>

My directory structure is very simple:

directory structure

I have tried almost everything, looked and adpated multiple tutorials, simplified the program to its skeleton, uninstalled and re-installed Flask, but still the Jinja Code comes up as text like so:
display

What am I missing here?

2

Answers


  1. Your code is fine, everything is set up correctly. It appears that you are manually opening your index.html file in the browser (i.e., double-clicking index.html). For your page to display correctly, you need to start your server and then navigate to the home route to see the correct page.

    Start the server:

    python app.py

    You should get some output like this:

     * Serving Flask app 'app'
     * Debug mode: on
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: xxx-xxx-xxx
    

    Then, open your browser and navigate to http://127.0.0.1:5000. The page should display correctly.

    Login or Signup to reply.
  2. I’d be glad to help you resolve the issue of Jinja code showing up as text in your Flask and HTML project. Here’s a breakdown of the potential causes and solutions:

    Autoescaping:

    By default, Jinja automatically escapes certain characters to prevent security vulnerabilities like cross-site scripting (XSS). This can lead to Jinja code appearing as text if not handled correctly.
    Solution:

    Use the |safe filter within your Jinja template to mark the message as safe for rendering. However, use this with caution as it bypasses escaping and potential security risks. Ensure you trust the source of the message before applying.

    HTML
    {% for mesg in get_flashed_messages() %}
        <h1>{{ mesg|safe }}</h1>  {% endfor %}
    

    Alternatively, consider using Flask’s with_appcontext function in your Python code to mark the context as trusted:

    Python
    from flask import Flask, flash, redirect, render_template, with_appcontext
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = '12345'
    
    @app.route('/')
    def index():
        with app.app_context():  # Mark context as trusted
            flash('Hello, this is a flash message!')
        return render_template('index.html')
    

    Template Rendering:

    Ensure you’re using render_template to render your index.html template.
    Debugging:

    Check Flask’s debug output for any errors or warnings that might point to the issue.

    Template Reloading:

    Enable Flask’s debug mode (default behavior with app.run(debug=True)) to automatically reload templates on changes. This can be helpful during development.

    Corrected Code Snippets:

    app.py:

    Python
    from flask import Flask, flash, redirect, render_template, with_appcontext
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = '12345'
    
    @app.route('/')
    def index():
        with app.app_context():
            flash('Hello, this is a flash message!')
        return render_template('index.html')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    index.html:

    HTML
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,   
     initial-scale=1.0">
        <title>Flash Message   
     Example</title>
    </head>
    <body>
        {% for mesg in get_flashed_messages() %}
            <h1>{{ mesg|safe }}</h1>  {% endfor %}
    </body>
    </html>
    

    Additional Tips:

    Consider using a template inheritance structure to share common layout elements across your templates.
    Explore other ways to display flash messages using CSS styling.
    By following these steps, you should be able to get your Jinja code to render correctly, displaying the flash message as intended in your HTML page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search