Craig Craig - 2 months ago 9
Python Question

jinja2 blocks not rendering in template

Ok so this is like a newbie question but I was trying out template inheritance with Jinja using Flask.

The problem I am running into is my blocks wont render in my base.html template.

This is my base.html

Code:

<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block body %}{% endblock %}
<h2>From Layout</h2>
</body>
</html>


This is my index.html that extends base.html

{% extends "base.html" %}

{% block title %} Home {% endblock %}

{% block content %}
<h1> Welcome home {name}</h1>
{% endblock %}


This is my main Flask file where I run my app from:

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
@app.route('/<name>')
def index(name="Mark"):
return render_template('index.html', name=name)


Have I missed out on something? Can't seem to figure out what I'm doing wrong.

Answer

Your index file has "block content" but your base file has "block body". Choose one or the other, but be consistent.

Once you've fixed that, you'll also need to fix how you display the name: the variable syntax is {{ name }}, not {name}.