Jinja Template Basics
Jinja looks and behaves mostly like Python. Special delimiters distinguish Jinja syntax from static data:{{ }}- Expression that will be output to the final document{% %}- Control flow statement likeifandfor{# #}- Comments (not included in output)
Flask configures Jinja to autoescape any data rendered in HTML templates. This means it’s safe to render user input - characters like
< and > will be escaped with safe values.The Base Layout
Create base template
Each page in the application will have the same basic layout. Instead of writing the entire HTML structure in each template, each template will extend a base template.Create Key features:
flaskr/templates/base.html:flaskr/templates/base.html
gis automatically available in templatesurl_for()is automatically available and generates URLs to views- The template loops over messages from
get_flashed_messages() - Three blocks are defined for child templates to override:
title,header, andcontent
Create register template
Create Key features:
flaskr/templates/auth/register.html:flaskr/templates/auth/register.html
{% extends 'base.html' %}tells Jinja that this template should replace the blocks from the base template- All rendered content must appear inside
{% block %}tags that override blocks from the base template - The
requiredattribute tells the browser not to submit the form until those fields are filled in
Test the Templates
Visit registration page
Test form validation
Try clicking the “Register” button without filling out the form - the browser will show an error message.Try removing the
required attributes from the template and click “Register” again. Instead of the browser showing an error, the page will reload and the error from flash() in the view will be shown.Template Organization
The base template is directly in thetemplates directory. To keep the others organized, templates for a blueprint are placed in a directory with the same name as the blueprint:
Useful Template Patterns
Nested Blocks
A useful pattern is to place{% block title %} inside {% block header %}. This sets the title block and then outputs the value of it into the header block:
Conditional Display
Check if a user is logged in to display different navigation:Form Data Persistence
Display previously submitted data when there’s a validation error:Default Values
Use theor operator to provide a default value:
