[파이썬] Chameleon 템플릿 사용

In today’s blog post, we will explore Chameleon, a powerful and flexible templating engine for Python. Chameleon allows you to separate the presentation logic from the business logic in your applications, making it easier to create dynamic web pages and generate HTML on the fly.

What is Chameleon?

Chameleon is a templating engine for Python that provides an efficient way to render HTML templates. It is designed to be fast and flexible, with a focus on performance and simplicity. Chameleon templates are written using HTML markup and special tags, which allow you to insert dynamic content and control the flow of the template.

Installing Chameleon

To get started with Chameleon, you’ll need to install it using pip, the Python package manager. Open your terminal or command prompt and type the following command:

pip install chameleon

Creating a Chameleon Template

To create a Chameleon template, we need to create a new file with a .pt extension. Suppose we want to create a template for a simple login page. We can create a file called login.pt and write the following code:

<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>Welcome to the login page</h1>
    <form method="post" action="">
        <input type="text" name="username" placeholder="Username" />
        <input type="password" name="password" placeholder="Password" />
        <input type="submit" value="Login" />
    </form>
</body>
</html>

In this template, we have added placeholders for the username and password inputs and a submit button for the login form.

Rendering the Chameleon Template

Now that we have created our Chameleon template, let’s render it using Python. Create a new Python file, import the necessary Chameleon modules, and add the following code:

from chameleon import PageTemplate

def render_template(template_name, context):
    with open(template_name, 'r') as file:
        template = PageTemplate(file.read())
        return template.render(**context)

context = {"title": "Login Page"}

rendered_html = render_template("login.pt", context)
print(rendered_html)

In this code, we define a render_template function that takes a template name and a dictionary of context variables. We open the template file, create a PageTemplate object, and render the template with the provided context. The rendered HTML is then printed to the console.

Conclusion

Chameleon provides a straightforward and efficient way to generate dynamic HTML templates in Python. It allows you to separate your application logic from the presentation layer, making your code easier to maintain and modify. With its simple syntax and fast performance, Chameleon is a great choice for web development projects.

In this blog post, we’ve only scratched the surface of what Chameleon can do. Explore the official documentation and tutorials to learn more about its features and capabilities. Happy templating with Chameleon!