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

如何创建嵌套Cookiecutter?内层模板生成遇属性缺失错误求助

解决嵌套Cookiecutter的报错问题

错误原因

运行外层Cookiecutter时,它会递归解析所有带{{cookiecutter.*}}的路径和文件内容。内层模板里的{{cookiecutter.analysis_name}}依赖内层模板的变量,但外层模板的上下文(context)中没有定义analysis_name,因此触发了'collections.OrderedDict object' has no attribute 'analysis_name'的错误。

解决方案

有两种可靠的方法实现你的嵌套模板需求:

方法一:让外层模板跳过渲染内层模板目录

在外层的cookiecutter.json中添加_copy_without_render配置,指定内层模板的路径,让外层Cookiecutter直接复制该目录下的所有内容,不进行模板渲染。

修改后的外层cookiecutter.json示例:

{
  "repo_name": "",
  "_copy_without_render": ["project_template/**/*"]
}

这个配置会告诉外层Cookiecutter:project_template下的所有文件和文件夹都直接复制,不解析其中的{{cookiecutter.*}}变量。

方法二:转义内层模板的变量路径

把内层模板的文件夹名{{cookiecutter.analysis_name}}修改为{{ "{{cookiecutter.analysis_name}}" }}。外层Cookiecutter渲染时,会把这个转义后的路径转换成{{cookiecutter.analysis_name}},保留内层模板的变量结构,不会试图解析analysis_name变量。

修改后的内层模板目录结构:

cookiecutter-for-analysis
├── cookiecutter.json
└── {{cookiecutter.repo_name}}
    ├── README.md
    ├── .gitignore
    └── project_template
        ├── cookiecutter.json
        └── {{ "{{cookiecutter.analysis_name}}" }}
            ├── README.md
            ├── pyproject.toml
            ├── .gitignore
            ├── notebooks
            └── sql

验证步骤

  1. 按上述任一方法修改外层模板结构。
  2. 运行外层模板生成命令:cookiecutter cookiecutter-for-analysis,输入repo_name后,成功生成外层目录。
  3. 进入外层目录:cd <你的repo_name>。
  4. 运行内层模板生成命令:cookiecutter project_template,输入analysis_name,即可在当前目录下生成对应的分析子文件夹。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:12:36