当前位置:首页 > Python > 正文

Python Jinja2模板渲染完全教程 - 从入门到实战

Python Jinja2模板渲染完全教程

什么是Jinja2?

Jinja2是一个现代的、设计友好的Python模板引擎,它被广泛用于Web开发框架如Flask和Django。Jinja2允许你创建动态HTML页面,通过将模板文件与数据结合生成最终的HTML内容。

安装Jinja2

使用pip命令安装Jinja2非常简单:

pip install Jinja2

基础语法

变量渲染

使用双大括号{{ variable }}渲染变量:

<h1>Welcome, {{ user.name }}!</h1>
<p>Your email is: {{ user.email }}</p>

控制结构

使用{% %}标签实现条件判断和循环:

{% if user.is_admin %}
    <div class="admin-badge">Administrator</div>
{% elif user.is_moderator %}
    <div class="moderator-badge">Moderator</div>
{% else %}
    <div class="user-badge">Regular User</div>
{% endif %}

<ul>
{% for item in navigation %}
    <li><a  href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>

模板继承

Jinja2的模板继承功能让你可以创建一个基础模板,然后在子模板中扩展或覆盖特定部分。

基础模板 (base.html)

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2023 by <a href="/">My Site</a>.
        {% endblock %}
    </div>
</body>
</html>

子模板 (page.html)

{% extends "base.html" %}

{% block title %}About Us{% endblock %}

{% block content %}
    <h1>About Our Company</h1>
    <p>We are a leading provider of...</p>
{% endblock %}

在Python中使用Jinja2

以下是在Python中渲染Jinja2模板的基本示例:

from jinja2 import Environment, FileSystemLoader

# 设置模板环境
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('greeting.html')

# 准备上下文数据
context = {
    'username': 'John Doe',
    'items': ['Apple', 'Banana', 'Orange'],
    'is_admin': True
}

# 渲染模板
output = template.render(context)
print(output)

实战示例:用户信息卡片

结合HTML、CSS和Jinja2创建一个用户信息卡片:

<div style="border:1px solid #ddd;border-radius:8px;padding:20px;max-width:300px;margin:20px auto;box-shadow:0 4px 8px rgba(0,0,0,0.1);">
    <div style="display:flex;align-items:center;margin-bottom:15px;">
        <img src="{{ user.avatar }}" alt="{{ user.name }}" style="width:60px;height:60px;border-radius:50%;margin-right:15px;">
        <div>
            <h3 style="margin:0;font-size:1.3rem;">{{ user.name }}</h3>
            <p style="margin:0;color:#777;">@{{ user.username }}</p>
        </div>
    </div>
    
    <p style="line-height:1.5;">{{ user.bio }}</p>
    
    <div style="margin-top:15px;display:flex;justify-content:space-between;">
        <div>
            <strong>{{ user.followers }}</strong> followers
        </div>
        <div>
            <strong>{{ user.following }}</strong> following
        </div>
        <div>
            <strong>{{ user.posts }}</strong> posts
        </div>
    </div>
    
    {% if user.is_verified %}
        <div style="margin-top:15px;color:#3498db;font-weight:bold;">
            ✓ Verified Account
        </div>
    {% endif %}
</div>

最佳实践

  • 将业务逻辑与模板分离 - 模板应该只负责显示数据
  • 使用模板继承来保持网站设计的一致性
  • 对用户输入进行适当的过滤和转义以防止XSS攻击
  • 为复杂的模板逻辑创建自定义过滤器和全局函数
  • 使用模板片段重用重复的UI组件
  • 在模板中使用注释说明复杂逻辑的目的

通过本教程,您已经学会了Jinja2的核心概念和使用方法。现在可以开始在项目中应用这些知识创建动态、高效的Web页面了!

发表评论