📜  flask render_template - Python (1)

📅  最后修改于: 2023-12-03 15:15:05.737000             🧑  作者: Mango

Flask Render Template - Python

When building a web application with Flask, rendering templates is a common task. Flask provides a built-in function render_template which allows us to render an HTML template with dynamic content. In this article, we will explore the basics of using render_template and discuss some best practices for using this feature in your Flask project.

Using Flask Render Template

To use render_template in your Flask project, you first need to import it from the Flask module as shown below:

from flask import Flask, render_template

app = Flask(__name__)

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

In this example, we have defined a basic Flask app with a single route / which renders the template index.html. When the user visits the root URL, Flask will render the index.html template and return the result to the user's web browser.

Passing Data to Template

In many cases, we want to render a template with dynamic content. Flask provides a mechanism for passing data to the template when rendering. The render_template function takes the template name and keyword arguments which will be used as variables in the template.

@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)

In this example, we have defined a route which takes a parameter name and passes it to the user.html template. In the template, we can reference the name variable using the Jinja2 syntax {{ name }}.

Template Inheritance

In larger applications, we may have multiple pages that share the same layout. Flask supports template inheritance which allows us to define a base template with common elements and extend it in child templates.

<!-- base.html -->
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>
<!-- index.html -->
{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block content %}
  <h1>Welcome to my website</h1>
{% endblock %}

In this example, we have defined a base template base.html which defines the basic structure of our pages. We have also defined a child template index.html which extends the base template and overrides the title and content blocks. When the index.html template is rendered using render_template, Flask will use the base template as a layout and inject the content from the child template.

Conclusion

render_template is a powerful feature of Flask which allows us to easily render HTML templates with dynamic content. By following best practices such as passing data to the template and using template inheritance, we can create complex web applications with ease using Flask.