0

I'm learning about template inheritance and I'm a little confused. When I navigate to index.html, I want the title to appear on the tab in my browser. And I want this functionality to be built into the base.html file, which I'm inheriting from, such that the function index on app.py need only be passed the argument title (and the html file name) to execute as described above.

For some reason, the code is not functioning as intended; the title is not present on the browser tab.

app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',title='index')

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

index.html:

<!DOCTYPE html>
{%extends "base.html"%}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
  </head>
  <body>

  </body>
</html>

base.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>

Both index.html and base.html are found in the templates folder as is necessary for jinja to function. No errors are being triggered, the title is simply not being formatted as intended.

What am I doing wrong?

jbuddy_13
  • 902
  • 2
  • 12
  • 34

2 Answers2

0

I figured it out, I needed to pull the title lines OUT of the block statement! Subtle but makes a big difference.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
    {%endblock%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
jbuddy_13
  • 902
  • 2
  • 12
  • 34
0

Your base.html has two <title> tags. Which isn't valid html. You'll want to remove the empty one and allow for the title to be passed as an argument in all cases.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title> <!-- Remove this line here! -->
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
Taylor Cochran
  • 439
  • 4
  • 16