How Flask handles templates versus static files

How Flask handles templates versus static files

If you are getting this error:

AttributeError: ‘function’ object has no attribute ‘html’

In Flask, there is no .html attribute on the app object or a function. Usually, this error happens when you try to just return the .html file or call render_template but accidentally type something like return render.html('index.html') or if you’ve named a variable render that is clashing with Flask’s built-in functions.

from flask import Flask

#initialize flask app
app = Flask(__name__)
#define route
@app.route('/')
def index():
    return index.html

if __name__ == '__main__':
    app.run(debug=True)
AttributeError: 'function' object has no attribute 'html'

1. Incorrect Function Call (Most Common)

You might be trying to use a syntax that doesn’t exist in Flask.

  • Wrong: return render.html('index.html')
  • Right: return render_template('index.html')

2. Variable Naming Conflict

Check if you have a function or a variable named render or template that is shadowing the import. If you define a function called render, and then try to call render.html, Python thinks you are trying to find an attribute inside your own function.

3. Missing Import

Ensure you have explicitly imported render_template from the flask library at the very top of your script:

Python

from flask import render_template

Pro-Tip: The Folder Structure

Flask is very picky about where your files live. If you are using render_template, your file structure must look like this:

  • Project Folder/
    • static/ (For CSS/Images)
    • app.py (Your Python code)
    • templates/ (Folder must be named exactly this)
      • index.html

Solution

from flask import Flask, render_template

#initialize flask app
app = Flask(__name__)
#define route
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)