Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Template Rendering

Flask Template Rendering

Concatenating HTML strings in Python code is both tedious and dangerous (prone to XSS vulnerabilities), so Flask integrates the Jinja2 template engine to solve this problem.

Templates let you separate business logic from page presentation, producing safer and more maintainable code.


render_template basics

render_template() is the most commonly used template rendering function in Flask.

Its first argument is the template filename, and subsequent keyword arguments are passed to the template as variables.

Example

File path: app.py

from

flask

import

Flask

,

render_template

app

=

Flask

(

name

)

@

app.

route

(

"/"

)

def

index

(

)

:

   

Render the templates/index.html template, passing the title and name variables

   

return

render_template

(

"index.html"

,

title

=

"RUNOOB homepage"

,

name

=

"World"

)

@

app.

route

(

"/user/"

)

def

profile

(

username

)

:

   

Pass the username from the URL to the template

   

return

render_template

(

"user.html"

,

username

=

username

,

posts

=

[

       

{

"title"

:

"Flask Getting Started"

,

"date"

:

"2026-05-01"

}

,

       

{

"title"

:

"Jinja2 Template"

,

"date"

:

"2026-05-10"

}

,

   

]

)

Template files are placed in the templates/ folder under the project directory:



runoob-flask-test/

├── app.py

└── templates/

    ├── index.html

    └── user.html

The content of index.html is:

Example ( index.html )

    {{ title }} - RUNOOB

   

{{ title }}

     

Hello {{ name }}。

Visit http://127.0.0.1:5000/. The output is:


Jinja2 basic syntax

Three core syntaxes in Jinja2 templates:

Syntax Purpose Example
{{ ... }} Output a variable value, with automatic HTML escaping {{ username }}
{% ... %} Control statements (if, for, block, etc.) {% if user %}
{# ... #} Comments, which do not appear in the rendered result {# This is a comment #}

Template example

Example ( user.html )

   

<p>{{ username }} - RUNOOB</p>

   

{{ username }}'s personal homepage

   

    {% if posts %}

       

Recent articles:

       

    {% else %}

       

No articles yet

    {% endif %}

   

   

Username in uppercase: {{ username|upper }}


Common filters

Filters are used to modify the output format of a variable and are invoked with the pipe character |.

Filter Purpose Example Output
upper Convert to uppercase {{ "hello"|upper }} HELLO
lower Lowercase conversion {{ "HELLO"|lower }} hello
title Capitalize the first letter {{ "hello world"|title }} Hello World
length Get the length {{ [1,2,3]|length }} 3
default Set a default value {{ name|default("Anonymous") }} Anonymous (when name is empty)
safe Mark as safe HTML (no escaping) {{ "Bold"|safe }} Render as bold text
join Concatenating Lists {{ ["a","b"]|join(",") }} a,b

Security Warning:safe This filter disables auto-escaping and should only be used when the data source is absolutely trusted. Never use it for user-submitted content; safe。


Auto-escaping - XSS protection

Jinja2 escapes HTML for all variable output by default, which is a key line of defense in Web security.

For example, if a user submits the username , it will be automatically converted to safe text during template rendering:





{{ username }}

Escaping applies to template files ending in .html, .htm, .xml, .xhtml, or .svg.


Template inheritance - eliminating duplicate code

Template inheritance is one of Jinja2's most powerful features; it lets you define a "base layout" and then fill in content through child templates.

This avoids repeating common parts such as the header, navigation, and footer on every page.

Base template (parent template)

Example

   

   

<p>{% block title %}RUNOOB Flask Tutorial{% endblock %}</p>

   

   

       

RUNOOB Flask Tutorial

       

   

   

   

    {% block content %}{% endblock %}

   

   

       

©

2026 RUNOOB.com

   

Child template (inheriting from the parent template)

Example

{% extends "base.html" %}

{% block title %}RUNOOB Tutorial - Home{% endblock %}

{% block content %}

   

Welcome to RUNOOB

   

{{ greeting }}

    {% if user %}

       

Current user: {{ user }}

    {% else %}

       

Please log in first

    {% endif %}

{% endblock %}

tag Purpose
{% extends "base.html" %} Declares that the current template inherits from base.html (must be placed on the first line)
{% block name %}...{% endblock %} Defines a region that can be overridden by child templates
{{ super() }} Calls the content of the parent template's block with the same name from within a child template's block

With template inheritance, you only need to modify base.html one place, and the common parts of all pages (such as navigation and footer) are updated automatically.


Built-in objects in templates

The following Flask objects can be used directly in templates without being passed through render_template():

object Description Example usage in a template
request The current request object {{ request.path }}
session Current session data {{ session.get("username") }}
g Request-level global variables {{ g.user }}
config Application configuration {{ config["APP_NAME"] }}
url_for() The URL generation function {{ url_for("index") }}
get_flashed_messages() Retrieve flash messages {% for msg in get_flashed_messages() %}...

Including other templates - include

Using {% include %} you can embed one template inside another:

Example

Example

<p>Page</p>

    {% include "_navbar.html" %}

   

Page content

   

This is the main content of the page.

Best Practices: Template inheritance (extends) is used for page-level layout reuse,include while include is used for component-level code reuse. Reusable components such as navigation bars and sidebars are well suited to include.


Complete example: Blog homepage

Integrate the above knowledge into a practical scenario:

Example

File path: app.py

from

flask

import

Flask

,

render_template

app

=

Flask

(

name

)

@

app.

route

(

"/"

)

def

index

(

)

:

   

Simulate article data in a database

    articles

=

[

       

{

"id"

:

1

,

"title"

:

"Flask Getting Started Guide"

,

"author"

:

"runoob"

,

"views"

:

1024

}

,

       

{

"id"

:

2

,

"title"

:

"Jinja2 Template Explained"

,

"author"

:

"admin"

,

"views"

:

512

}

,

       

{

"id"

:

3

,

"title"

:

"RESTful API design"

,

"author"

:

"runoob"

,

"views"

:

256

}

,

   

]

   

return

render_template

(

"blog.html"

,

articles

=

articles

)

Example

{% extends "base.html" %}

{% block title %}RUNOOB Blog{% endblock %}

{% block content %}

   

Latest Articles

    {% if articles %}

        {% for article in articles %}

           

           

1000 %}style="background:#fff3cd;"{% endif %}>

               

{{ article.title }}

               

Author: {{ article.author }} | Views: {{ article.views }}

               

                {% if not loop.last %}

                   


                {% endif %}

           

        {% endfor %}

    {% else %}

       

No articles yet; please come back later.

    {% endif %}

{% endblock %}


Jinja2 special variables

Variables Description
loop.index The current loop index, starting from 1
loop.index0 The current loop index, starting from 0
loop.first Whether this is the first iteration
loop.last Whether this is the last iteration
loop.length The total length of the sequence