flask
  1. flask-templates

Web Templating in Flask

Web Templating in Flask refers to the process of using a pre-built layout or design for creating web pages. Flask offers built-in support for web templating and supports various templating engines such as Jinja2, Mako, and Cheetah.

Syntax

The general syntax for using templates in Flask is as follows:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

In the above code snippet, render_template function is used to render a template named index.html. This function takes the name of the template file as a parameter and returns the HTML content that is generated by rendering the template.

Example

Let's take an example of a simple Flask application that uses templates.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    name = 'John Doe'
    return render_template('index.html', name=name)

if __name__ == '__main__':
    app.run()

In the example above, the home() function retrieves the name of the user and passes it as a variable to the template. The template index.html can then use this variable to display a personalized message.

Output

When you run the Flask application, it will render the index.html template with the provided variable and display it in the browser. The output will look like this:

<!doctype html>
<html>
  <head>
    <title>Flask App</title>
  </head>
  <body>
    <h1>Hello John Doe!</h1>
  </body>
</html>

Explanation

In the above example, the Flask application uses the render_template function to render the index.html template and pass the name variable to it. The template then uses the {{ name }} syntax to display the personalized message.

<!doctype html>
<html>
  <head>
    <title>Flask App</title>
  </head>
  <body>
    <h1>Hello {{ name }}!</h1>
  </body>
</html>

Use

Templates in Flask are used for creating dynamic web pages that can receive input from the user and display personalized output. Templates can be used for creating pages such as login pages, registration pages, user profiles, and much more.

Important Points

  • Flask supports various web templating engines such as Jinja2, Mako, and Cheetah.
  • Templates in Flask can be used for creating dynamic web pages that can receive input from the user and display personalized output.
  • The render_template function is used to render a template in Flask.

Summary

Web templating in Flask allows you to create dynamic web pages with ease. Flask supports various templating engines, and the render_template function is used to render a template in Flask. Templates can be used to create pages such as login pages, registration pages, user profiles, and much more.

Published on: