KJW
KJW

Reputation: 15251

Flask: render_template with path

I have several different templates that I'm trying to use for my flask app.

I have tried the following but it seems to only look directly inside /templates and not /templates/folder1, templates/folder2 etc.

 return render_template('index.html', template_folder='folder1')
 return render_template('folder1/index.html')

both do not work as expected, how can I specify the sub folder of different templates.

Upvotes: 15

Views: 43209

Answers (3)

Yuqin Peng
Yuqin Peng

Reputation: 53

Be sure the Python file and Template folder are all under the same working directory folder.

Upvotes: 1

naaman
naaman

Reputation: 942

The template folder can be specified when creating the Flask app (or Blueprint):

from flask import Flask
app = Flask(__name__, template_folder='folder1')

Source: http://flask.pocoo.org/docs/0.12/api/#application-object

from flask import Blueprint
auth_blueprint = Blueprint('auth', __name__, template_folder='folder1')

Source: http://flask.pocoo.org/docs/0.12/blueprints/#templates

The template_folder is relative to where the app/blueprint is located. Use the os library to create paths to template folders outside of the app/blueprint directory.

eg.

import os
APP_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(APP_PATH, 'templates/')
  • run from subdirectory of app root
  • APP_PATH retrieves parent directory path (app root)

Upvotes: 30

George Pazdral
George Pazdral

Reputation: 90

I think Sean is right, but also: have you tried double quotes? I'm using Blueprint, so it may be different, but this is what mine looks like:

return render_template("users/register.html")

so yours may be:

return render_template("folder1/index.html")

Upvotes: -14

Related Questions