The render_template function helps you show HTML pages in your web app easily. It connects your Python code with HTML files to create web pages.
Render_template function in Flask
render_template(template_name, **context)
template_name is the filename of your HTML file inside the templates folder.
**context means you can pass many named values to use inside the HTML page.
render_template('index.html')render_template('profile.html', username='Alice')
render_template('items.html', items=['apple', 'banana', 'cherry'])
This Flask app shows a welcome page that greets the user by name. The render_template function sends the name variable to the HTML file welcome.html.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): user = 'Sam' return render_template('welcome.html', name=user) if __name__ == '__main__': app.run(debug=True)
Always put your HTML files inside a folder named templates in your project.
You can pass many variables to the template by adding more named arguments to render_template.
Use Jinja2 syntax inside your HTML files to use the passed data, like {{ name }}.
render_template connects Python code with HTML pages in Flask.
It lets you send data from your app to the page to show dynamic content.
Keep your HTML files in the templates folder for Flask to find them.