[파이썬] Flask HTML 템플릿 렌더링

Flask is a popular web framework in Python that allows you to easily build web applications. One of the key features of Flask is its ability to render HTML templates dynamically. In this blog post, we will explore how to use Flask to render HTML templates in a Python application.

Setting up Flask

Before we dive into HTML template rendering, let’s quickly go over the setup process for Flask. First, you need to install the Flask package. You can do this by running the following command in your terminal:

pip install flask

Once Flask is installed, you can proceed to create a new Flask application. Here’s an example of a basic Flask application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

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

In this example, we are creating a Flask application and defining a route for the root URL (“/”). When a user visits the root URL, the hello_world function will be executed, and the string “Hello, World!” will be returned as a response.

HTML Template Rendering

To render HTML templates in Flask, you need to create a templates folder in your application directory. Inside the templates folder, you can create HTML template files with the .html extension. Flask will automatically search for templates in this folder.

Let’s create a simple HTML template called index.html. Inside this template, we will have a placeholder for dynamic content:


<!DOCTYPE html>
<html>
<head>
    <title>Flask Template Rendering</title>
</head>
<body>
    <h1>Welcome to our website</h1>
    <p>{{ content }}</p>
</body>
</html>

In this template, we have a placeholder {{ content }} that will be replaced with dynamic content when the template is rendered.

Now, let’s modify our Flask application to render this HTML template. We will pass some dynamic content to the template and render it using the render_template function:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    content = "This is some dynamic content!"
    return render_template('index.html', content=content)

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

In this updated version of our Flask application, we import the render_template function from Flask and use it to render the index.html template. We pass the dynamic content as a parameter to the render_template function.

When a user visits the root URL, Flask will render the index.html template with the dynamic content and return it as a response.

Conclusion

Flask provides a simple and efficient way to render HTML templates in Python web applications. By using the render_template function, you can easily pass dynamic content to your templates and create dynamic web pages.

I hope this blog post has helped you understand how to render HTML templates in Flask. Happy coding!

References