How to Return HTML in Flask: Simple Guide with Examples
In Flask, you can return HTML by using the
render_template function to serve HTML files from a templates folder or by returning a raw HTML string directly from a route function. The render_template method is preferred for larger HTML content and better organization.Syntax
To return HTML in Flask, you typically use the render_template function or return a string containing HTML directly.
render_template('filename.html'): Renders an HTML file from thetemplatesfolder.- Returning a string: You can return raw HTML as a string directly from a route.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): # Return HTML file return render_template('index.html') @app.route('/raw') def raw_html(): # Return raw HTML string return '<h1>Hello, Flask!</h1><p>This is raw HTML.</p>'
Example
This example shows a Flask app returning HTML using both render_template and a raw HTML string. The templates/index.html file contains simple HTML content.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/raw') def raw_html(): return '<h1>Hello, Flask!</h1><p>This is raw HTML returned directly.</p>' if __name__ == '__main__': app.run(debug=True)
Output
When you visit http://localhost:5000/, the browser shows the HTML from index.html file.
When you visit http://localhost:5000/raw, the browser shows the raw HTML string content.
Common Pitfalls
- Not placing HTML files inside a folder named
templatescausesrender_templateto fail. - Returning raw HTML strings is okay for small snippets but hard to maintain for bigger pages.
- Forgetting to import
render_templatefrom Flask leads to errors. - Not running the Flask app with
debug=Trueduring development can make debugging harder.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): # Wrong: render_template not imported # return render_template('index.html') # This will cause an error # Right way: return '<h1>Fallback HTML</h1>'
Quick Reference
Summary tips for returning HTML in Flask:
- Use
render_templatefor HTML files stored intemplates/. - Return raw HTML strings for very simple responses.
- Keep HTML files organized in the
templatesfolder. - Always import
render_templatewhen using it. - Run Flask with
debug=Trueduring development for easier error tracking.
Key Takeaways
Use render_template to return HTML files from the templates folder in Flask.
You can return raw HTML strings directly for simple responses.
Always place HTML files inside a folder named templates.
Import render_template from flask to avoid errors.
Run Flask with debug=True during development for easier debugging.