Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask Template Inheritance tutorial

I am running through the flask tutorial and I can not seem to get the Template Inheritance to work. below are the examples of my code

My base.html is:

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
</head>
<body>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
        {% endblock %}
    </div>
</body>
</html>

my child Temp is:

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
      Welcome to my awesome homepage.
    </p>
{% endblock %}

my flask script is:

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


@app.route('/')
def home():
    return render_template("base.html")

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

Is there something specifically I should be doing regarding how I am incorporating the child template? Or should I be rendering the base template differently?

like image 910
FPcond Avatar asked Dec 20 '15 04:12

FPcond


People also ask

Can we inherit templates in Flask?

Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

How do I use a template in Flask?

html template file in a directory called templates inside your flask_app directory. Flask looks for templates in the templates directory, which is called templates , so the name is important. Make sure you're inside the flask_app directory and run the following command to create the templates directory: mkdir templates.

How implement inheritance in template file explain with application?

To use Template Inheritance we must first create a base template. A base template is just a simple skeleton that we will be used as a base for all other pages on our site. A base template defines areas where content can be inserted into. In Django, we define this area using the block tag.


1 Answers

Jinja extends works (superficially) like Python subclassing. You don't get an instance of a subclass when you instantiate a parent class, and you don't get the result of a child template when rendering the base template. Render the child template instead.

return render_template('child.html')
like image 169
davidism Avatar answered Oct 25 '22 13:10

davidism