flask: Method `render_template` does not use blueprint specified `template_folder`

  1. File structure:
project -
      - templates \
                - a \
                      search.html
                - b \
                      search.html
      - start.py
      - myapplication \
                - test.py 
  1. Start file:
# start.py
from flask import Flask
from myapplication.test import test_blueprint

app = Flask(__name__)
app.register_blueprint(test_blueprint)
  1. my application
# test.py
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

test_blueprint = Blueprint('test_blueprint', __name__,
                        template_folder='absolute_path_to_project/templates/a')  
                        # YES, I specified the absolute path to the template a

@test_blueprint.route('/test')
def show():
    try:
        return render_template(''search.html") # HERE is the problem
    except TemplateNotFound:
        abort(404)

Is this a problem? # Actually, I want to render a/search.html # But, render_template() does not use test_blueprint’s template_folder # render_template() search the template list, find the first search.html, then render # So, maybe render a/search.html or b/search.html # This depend on the sequence of the template list

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 57 (34 by maintainers)

Most upvoted comments

For anyone who stumbles upon this as I did many months ago, and are as perfectly alright violating the blueprint contract as they are understanding of it’s implications, I ended up writing a tiny Flask plugin to solve this issue.

Hopefully this will come in useful to you, future Googler.

Your expectation is not how template lookups work. You create a subdirectory in order to distinguish the blueprint templates. You pass a template folder to a blueprint in order to append it to the search path, not to just use those templates. So don’t pass your subdirectory as the template folder, pass it during render template or use the subclass I wrote above.

my_project/
    my_app/
        __init__.py
        templates/
            index.html
        users/
            __init__.py
            templates/
                users/
                    index.html
bp = Blueprint('users', __name__, template_folder='templates')

@bp.route('/')
def index():
    return render_template('users/index.html')