Flask Template Rendering API

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

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


render_template

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

Parameter Type Description
template_name_or_list str / list 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) Renders a template from a file, returns an HTML string.
render_template_string(source, **context) Renders a template from a string, suitable for embedded templates.
stream_template(template_name_or_list, **context) Streams the rendered template, returns a generator. Suitable for large pages.
stream_template_string(source, **context) Streaming Rendering of String Templates
get_template_attribute(template_name, attribute) Gets a macro or variable from the template. Can call Jinja2 macros from Python.

Built-in Objects in Templates

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

Object Description
request Current request object
session Current Session Object
g Request-level global object
config Application configuration dictionary
url_for URL Generation Function
get_flashed_messages Flask Message Retrieval Function

Code Examples

Example

from flask import Flask, render_template, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html",
                          title=EXAMPLE Home,
                          posts=[{"id": 1, "title": Article A},
                                 {"id": 2, "title": Article B}])

@app.route("/inline")
def inline_template():
    # Render from string (template content written directly in code)
    return render_template_string("""
        <h1>Hello, {{ name }}!</h1>
        <p>Welcome to EXAMPLE.</p>
    """
, name="World")

@app.route("/stream")
def stream_large_page():
    # Stream-render large pages, generating and sending on the fly
    return stream_template("large_report.html",
                          items=get_10k_items())
other extensions