Passing HTML to template using Flask/Jinja2
In this article, we will discuss how to pass HTML content from a Flask application to a template using Jinja2.
Step 1: Setting up Flask
First, make sure you have Flask installed. If not, you can install it using pip:
pip install Flask
Step 2: Creating a Flask application
Create a new file, for example, app.py, and add the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
html_content = '<h2>Hello, world!</h2>'
return render_template('template.html', html_content=html_content)
if __name__ == '__main__':
app.run(debug=True)
Step 3: Creating a template
Create a new file named template.html in the templates folder of your Flask application directory. Add the following code to template.html:
<!DOCTYPE html>
<html>
<head>
<title>Passing HTML to template using Flask/Jinja2</title>
</head>
<body>
{{ html_content | safe }}
</body>
</html>
Step 4: Running the Flask application
Run the Flask application using the following command:
python app.py
Open a web browser and navigate to http://127.0.0.1:5000/. You should see the HTML content “Hello, world!” displayed in the browser.
Conclusion
By following the steps above, you can pass HTML content from a Flask application to a template using Jinja2 easily. This can be useful for dynamically rendering HTML content in your web applications.