Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: render_template with path

Tags:

flask

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.

like image 398
KJW Avatar asked Feb 13 '14 21:02

KJW


1 Answers

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)
like image 184
naaman Avatar answered Sep 28 '22 03:09

naaman