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

Flask Template Rendering API

Flask Template Rendering API

Flask uses the Jinja2 engine to render templates, embedding Python data into HTML pages.

Template files are placed in the templates/ folder at the project root by default.


render_template

The most commonly used template rendering function; loads a template from a file and renders it.

Parameters Type Description
template_name_or_list str / list The template filename (relative to the templates folder), or a list of template names (returns the first one that exists)
**context Keyword arguments Variables passed to the template, such as title="Hello", user=user_obj

All rendering functions

function Description
render_template(template_name_or_list, **context) Render a template from a file, returning an HTML string
render_template_string(source, **context) Render a template from a string, suitable for embedded templates
stream_template(template_name_or_list, **context) Stream-render a template, returning a generator. Suitable for large pages
stream_template_string(source, **context) Stream-render a string template
get_template_attribute(template_name, attribute) Get a macro or variable from a template. Jinja2 macros can be called from Python

Built-in objects in templates

The following objects are available in templates without being passed explicitly:

object Description
request The current request object
session The current Session object
g Request-level global objects
config The application configuration dictionary
url_for The URL generation function
get_flashed_messages The Flask message retrieval function

Code Example

Example

from

flask

import

Flask

,

render_template

,

render_template_string

app

=

Flask

(

name

)

@

app.

route

(

"/"

)

def

index

(

)

:

   

return

render_template

(

"index.html"

,

                          title

=

"RUNOOB homepage"

,

                          posts

=

[

{

"id"

:

1

,

"title"

:

"Article A"

}

,

                                 

{

"id"

:

2

,

"title"

:

"Article B"

}

]

)

@

app.

route

(

"/inline"

)

def

inline_template

(

)

:

   

Render from a string (template content written directly in the code)

   

return

render_template_string

(

"""
       

Hello, {{ name }}!


       

Welcome to RUNOOB.


    """

,

name

=

"World"

)

@

app.

route

(

"/stream"

)

def

stream_large_page

(

)

:

   

Stream-render a large page, sending it as it is generated

   

return

stream_template

(

"large_report.html"

,

                          items

=

get_10k_items

(

)

)