0
0
Flaskframework~5 mins

Render_template function in Flask

Choose your learning style9 modes available
Introduction

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.

When you want to display a web page to users in a Flask app.
When you need to send data from Python to an HTML page.
When you want to reuse HTML layouts with different content.
When you want to separate your Python logic from your page design.
Syntax
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.

Examples
Render a simple HTML page without extra data.
Flask
render_template('index.html')
Send the username 'Alice' to the HTML page to show it dynamically.
Flask
render_template('profile.html', username='Alice')
Pass a list of items to display them in the page.
Flask
render_template('items.html', items=['apple', 'banana', 'cherry'])
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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 }}.

Summary

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.