Jinja2 是一个功能强大的 Python 模板引擎,广泛用于生成动态内容。以下是其核心方法及实际应用场景的详细说明:
1. 模板渲染
- 方法:
Template.render(**context)
- 作用: 将模板与上下文数据结合,生成最终内容。
- 场景: 渲染简单的文本或 HTML。
- 示例:
from jinja2 import Template template = Template("Hello, {{ name }}!") output = template.render(name="Alice") print(output) # 输出: Hello, Alice!
2. 变量替换
- 语法:
{{ variable }}
- 作用: 插入变量值,支持对象属性、字典键、列表索引。
- 场景: 动态显示用户信息。
- 示例:
<!-- 模板 --> <p>用户名: {{ user.name }}, 邮箱: {{ user['email'] }}</p>
context = {"user": {"name": "Bob", "email": "bob@example.com"}} template.render(user=context["user"])
3. 控制结构
循环 (for
)
- 语法:
{% for item in list %} ... {% endfor %}
- 场景: 遍历商品列表。
- 示例:
<ul> {% for product in products %} <li>{{ product.name }} - ¥{{ product.price }}</li> {% endfor %} </ul>
products = [{"name": "笔记本", "price": 20}, {"name": "钢笔", "price": 5}] template.render(products=products)
条件 (if
)
- 语法:
{% if condition %} ... {% else %} ... {% endif %}
- 场景: 根据用户登录状态显示内容。
- 示例:
{% if user_logged_in %} <p>欢迎回来!</p> {% else %} <a href="/login">登录</a> {% endif %}
4. 模板继承
- 语法:
{% extends "base.html" %}
和{% block content %} ... {% endblock %}
- 作用: 实现页面布局复用。
- 场景: 基础模板定义通用结构,子模板填充内容。
- 示例:
<!-- base.html --> <html> <head><title>{% block title %}默认标题{% endblock %}</title></head> <body>{% block content %}{% endblock %}</body> </html> <!-- child.html --> {% extends "base.html" %} {% block title %}用户中心{% endblock %} {% block content %}<h1>个人资料</h1>{% endblock %}
5. 宏(Macro)
- 语法:
{% macro name(...) %} ... {% endmacro %}
- 作用: 定义可复用的代码片段,类似函数。
- 场景: 生成表单输入字段。
- 示例:
{% macro input(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} <!-- 使用宏 --> {{ input('username') }} {{ input('password', type='password') }}
6. 包含(Include)
- 语法:
{% include 'header.html' %}
- 作用: 引入其他模板内容。
- 场景: 共享导航栏或页脚。
- 示例:
<!-- main.html --> <body> {% include 'navbar.html' %} <div>页面主体内容</div> </body>
7. 过滤器
- 语法:
{{ variable|filter_name }}
- 作用: 格式化变量值。内置过滤器如
capitalize
、upper
、lower
。 - 场景: 格式化日期或金额。
- 示例:
自定义过滤器:{{ "hello world"|capitalize }} <!-- 输出: Hello world --> {{ 1000|currency }} <!-- 假设自定义过滤器,输出: $1,000.00 -->
def currency_filter(value): return f"${value:,.2f}" env = Environment(loader=...) env.filters['currency'] = currency_filter
8. 设置变量
- 语法:
{% set variable = value %}
- 场景: 在模板中计算中间值。
- 示例:
{% set total_price = items|sum(attribute='price') %} <p>总价: {{ total_price }}</p>
9. 测试函数
- 语法:
{% if variable is test_name %}
- 作用: 检查变量状态,如
defined
、none
、even
。 - 示例:
{% if user is defined %} <p>用户已登录</p> {% endif %}
10. 自定义全局函数
- 方法: 通过
Environment
添加全局函数。 - 场景: 在模板中调用复杂逻辑。
- 示例:
def get_current_time(): import datetime return datetime.datetime.now() env.globals['current_time'] = get_current_time
<!-- 模板中直接调用 --> <p>当前时间: {{ current_time() }}</p>
11. 自动转义
- 配置:
autoescape=True
(默认启用) - 作用: 防止 XSS 攻击,自动转义 HTML 字符。
- 示例:
from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape(['html', 'xml']))
总结
Jinja2 通过灵活的语法和丰富的功能,极大简化了动态内容的生成。无论是构建 Web 页面、生成电子邮件内容,还是配置文件模板,合理利用继承、宏、过滤器等特性,都能显著提升代码复用性和可维护性。