0
0
FlaskHow-ToBeginner · 3 min read

How to Render Template in Flask: Simple Guide

In Flask, you render an HTML template using the render_template function from the flask module. You call render_template('filename.html') inside a route function to return the HTML page to the browser.
📐

Syntax

The basic syntax to render a template in Flask is:

  • render_template('template_name.html'): Loads the HTML file from the templates folder.
  • This function returns the HTML content to the browser.
  • You use it inside a route function to display pages.
python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')
💻

Example

This example shows a simple Flask app that renders an index.html template when you visit the home page.

The index.html file must be placed inside a folder named templates in the same directory as your Python script.

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
Output
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) When you open this URL in a browser, it shows the content of index.html.
⚠️

Common Pitfalls

  • Template folder missing: Flask looks for templates in a folder named templates. If this folder is missing or misnamed, Flask will raise a TemplateNotFound error.
  • Wrong template filename: The filename in render_template must exactly match the HTML file name including extension.
  • Not returning the render_template call: Forgetting to return the result of render_template will cause the route to return None and show a server error.
python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    render_template('index.html')  # Missing return keyword

# Correct way:
@app.route('/correct')
def correct():
    return render_template('index.html')
📊

Quick Reference

Remember these key points when rendering templates in Flask:

  • Place HTML files inside a templates folder.
  • Use return render_template('file.html') inside route functions.
  • Template filenames are case-sensitive and must include the extension.
  • You can pass variables to templates as additional arguments.

Key Takeaways

Always place your HTML files inside a folder named 'templates' in your project.
Use 'return render_template("filename.html")' inside your Flask route functions to display pages.
Ensure the template filename matches exactly and includes the file extension.
Never forget to return the render_template call; otherwise, Flask will not send the page.
You can pass data to templates by adding extra arguments to render_template.