Home > database >  Jinja, templates inheritance and Flask blueprints: how to ectend the parent template from child html
Jinja, templates inheritance and Flask blueprints: how to ectend the parent template from child html

Time:11-28

I am using Jinja and Flask blueprints. However, I have issues rendering the child templates (albums.html) when I let it inherit from the parent (base.html) and get a TemplateNotFound error.

I tried to use relative paths and absolute paths inside {% extends 'path' %} and also googled but didn't find a solution.

My app is structured in this way:

flask/
  app.py
  statc/
    templates/
       base.html
  blueprints/
    albums/
       __init__.py
       templates/
          albums.html
       routes.py

The base.html file is very simple:

<!-- language-all: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% block title %}{{ title }}{% endblock%}</title>
    <!-- what shows up on search engine -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="static/css/style.css">
</head>

<body>
    <header>
        {% block header %}
        <h1>{{header}}</h1>{% endblock%}
    </header>
    <main> <h1> Hello </h1> </main>
    <footer> Some footer </footer>
</body>

The child template (albums.html) looks like this:

{% extends "static/templates/base.html" %} 
{% block title %}{{title}}{% endblock %} 
{% block header %}{{header}} {% endblock %}

And the routes.py file looks like this:

from flask import Blueprint, render_template, abort, url_for
from jinja2.exceptions import TemplateNotFound

album_page = Blueprint('album_page', __name__,
                       template_folder='./templates/albums')
                       
@album_page.route('/albums')
def albums():
    try:
        context = {
            'title': 'Albums',
            'header': 'Albums'
        }
        return render_template('albums.html', **context)
    except TemplateNotFound:
        print('error')
        abort(404)

However I get a TemplateNotFound error. Is there a way to make Jinja search in the static folder outside of the blueprints' package? Thank you.

CodePudding user response:

Within a Blueprint, template_folder is relative to the Blueprint. So either change

template_folder='./templates/albums'

to

template_folder='templates'

or change

return render_template('albums.html', **context)

to return render_template('templates/albums.html', **context)

and add an extra templates directory, moving albums.html into that.

I'd do the former, since the latter clutters things needlessly.

CodePudding user response:

The issue was solved by moving the templates folder from the static folder to the root of the project, and then simply call {% extends "base.html" %} inside albums.html

  • Related