Web Technologies/2021-2022/Laboratory 9

Dynamic pages (or dynamic content) display different content (and different layouts) based on various chosen parameters.

This Laboratory shows the usage of Jinja2 template inheritance and Flask-SQLAlchemy for creating content based on data found in an SQLite database.

Jinja2 template inheritance
One of the most important features of Jinja is template inheritance. This mechanism allows for the creation of a template skeleton containing the common elements for pages, allowing for the declaration of various block sections which child templates (the templates that inherit the base template) can override. Blocks are defined using the {% block %} ... {% endblock %} directives

Examples
Defining a base template (base.html): Overriding the base template (post.html): Overriding the base template (posts.html): Template inheritance in a sense resembles the inheritance concept from Object-Oriented Programming.

It helps with reduction of the codebase, as all the common elements can be placed in the base template.

Flask-SQLAlchemy creating and populating an SQLite database
As seen previously, in Laboratory 7, Flask-SQLAlchemy provides an Object-Relational Mapper, and ways to define Models and relationships between models.

In order to be able to use the templates in the template inheritance examples, we must first build the User and Post models, as well as define a script to create and populate the SQLite database, and routes for Flask.

Definition of the models: NOTE: The user_id attribute in the Post model is created as a Foreign Key. Additionally, the posted_by attribute in the User model is using db.relationship. Making it point to a query result for the corresponding field in the User table. Therefore, completing the relationship between the User -> Post tables (A user holds one or multiple posts).

Flask routing here is based on using Flask-SQLAlchemy queries to retrieve all or individual posts, which are to be rendered by the appropriate templates. The script responsible to create the database and add entries (based on the defined models) is:

The current directory structure of the files should look like: Useful links:

Dynamic_web_page

Jinja2 Template Inheritance

Flask-SQLAlchemy Model declaration and relationships