You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中配置Cheetah?求实现变量/列表文本输出的教程

Django + Cheetah 简单配置教程(输出变量/列表文本)

1. 安装依赖

先确保安装好所需的包:

pip install Cheetah3 django

2. 配置Django使用Cheetah模板引擎

打开项目的settings.py,修改TEMPLATES配置,添加Cheetah模板加载器:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates/'],  # 指向你的模板目录
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'loaders': [
                # 优先加载Cheetah模板(后缀通常为.tmpl)
                ('Cheetah.Template.DjangoTemplateLoader', {
                    'template_dirs': ['templates/'],
                }),
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

3. 创建Cheetah模板文件

在项目根目录的templates文件夹下新建hello.tmpl文件,写入以下内容:

<html>
<body>
    <h1>Hello, $name!</h1>
    <p>列表内容:</p>
    <ul>
        #for item in $items
            <li>$item</li>
        #end for
    </ul>
</body>
</html>
  • Cheetah用$变量名调用上下文变量
  • 循环语法为#for ... in ... + #end for

4. 编写视图函数

在app的views.py中添加视图:

from django.shortcuts import render

def hello(request):
    # 准备要传递给模板的上下文数据
    context = {
        'name': 'World',
        'items': ['Apple', 'Banana', 'Cherry']
    }
    # 渲染Cheetah模板
    return render(request, 'hello.tmpl', context)

5. 配置URL路由

在项目的urls.py中添加路由规则:

from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello, name='hello'),
]

6. 运行测试

启动Django开发服务器:

python manage.py runserver

访问http://localhost:8000/hello/,就能看到输出的变量和列表内容了。

注意事项

  • 确保templates目录路径在settings.py的DIRS中正确配置
  • Cheetah语法与Django原生模板语法差异较大,写模板时注意区分
  • 如果出现模板找不到的问题,检查模板加载器的顺序和路径是否匹配

内容的提问来源于stack exchange,提问作者Nikos Chalevas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:05:34