[파이썬] Flask Jinja2 템플릿 엔진

In Flask, the Jinja2 template engine is used to create dynamic web pages. It is a powerful and flexible templating language that allows you to easily generate HTML or other text-based formats using Python code.

Setting up Flask

Before we start using the Jinja2 template engine, we need to set up a basic Flask application. Here’s an example of how you can do that:

from flask import Flask, render_template

app = Flask(__name__)

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

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

In the above code, we import the Flask class and the render_template function from Flask. We then create a Flask app and define a route for the root URL (“/”). Finally, we create a function to handle this route and return the rendered template.

Creating a Jinja2 Template

To create a Jinja2 template, we need to create an HTML file with the desired structure and placeholders for dynamic content. These placeholders are known as template variables.

Let’s create a simple index.html template:


<!DOCTYPE html>
<html>
<head>
    <title>Flask Jinja2 Example</title>
</head>
<body>
    <h1>Welcome to my Flask Jinja2 example!</h1>
    <p>{{ message }}</p>
</body>
</html>

In the above template, we have a template variable message inside double curly braces ``. This variable can be dynamically replaced with content provided by the Flask app.

Rendering the Template

Now that we have our Flask app and Jinja2 template ready, we need to update our index function to render the template with dynamic data. Here’s an example:

@app.route('/')
def index():
    message = "Hello, World!"
    return render_template('index.html', message=message)

In this updated code, we’ve defined a variable called message and passed it as a parameter to render_template. This will make the value of message accessible inside the Jinja2 template.

Using Template Variables

To use the template variable inside the template, we can simply put its name inside the double curly braces {{ }}. For example, to display the message variable in our template, we can do:


<p>{{ message }}</p>

When the template is rendered, the message variable will be replaced with its value (“Hello, World!”) and the resulting HTML will be sent to the client.

Conclusion

Flask and the Jinja2 template engine make it easy to build dynamic web pages in Python. By using template variables, you can separate the logic from the presentation, allowing for more maintainable and scalable web applications.

I hope this tutorial has provided you with a good introduction to using the Jinja2 template engine in Flask. Happy coding!