2

我正在用 Python 构建一个 cookiecutter 模板,现在相当简单,看起来像这样:

├── {{ cookiecutter.project_name }}
│    └── test.py
│
└── cookiecutter.json

当我在命令行上运行 cookiecutter 命令并将其指向此模板时,它会正确地询问我的project_name输入。但是,问题是在我的test.py脚本中,还有一个带有双花括号的打印语句,所以最后,cookiecutter 命令失败,并出现以下错误:

  File "./test.py", line 73, in template
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got ':'
  File "./test.py", line 73
    print(('{{"RequestId":"{0}", '

有没有办法告诉 cookiecutter 省略某些花括号?

4

1 回答 1

1

来自 cookiecutter 的Troubleshooting 文档(或来自底层Jinja 模板文档),以防止 cookiecutter 错误地解析大括号{{{模板:

确保你正确地逃避事情,像这样:

{{ "{{" }}

或这个:

{{ {{ url_for('home') }} }}

有关更多信息,请参阅http://jinja.pocoo.org/docs/templates/#escaping

如果模板是这样的:

marker = '{{'
print('{{RequestId:{0}, ')
print('The value should be in braces {{{cookiecutter.value}}}')

大括号需要像这样转义:

marker = '{{ "{{" }}'
print('{{ "{{" }}RequestId:{0}, ')
print('The value should in braces {{ "{" }}{{cookiecutter.value}}{{ "}" }}')

以便它正确生成:

$ cat template/\{\{\ cookiecutter.project_name\ \}\}/test.py
marker = '{{ "{{" }}'
print('{{ "{{" }}RequestId:{0}, ')
print('The value should in braces {{ "{" }}{{cookiecutter.value}}{{ "}" }}')

$ cookiecutter template
project_name [myproject]: 
value [the_value]: 123456

$ cat myproject/test.py
marker = '{{'
print('{{RequestId:{0}, ')
print('The value should in braces {123456}')

{另一种选择是,您可以告诉 cookiecutter 跳过整个test.py 文件,方法是将其添加到Copy without Render列表(可从 cookiecutter 1.1+ 获得),而不是转义 test.py 中的每个文件:

为了避免渲染 cookiecutter 的目录和文件,可以在cookiecutter.json中使用_copy_without_render键。

{
   "project_slug": "sample",
   "_copy_without_render": [
       "*.html",
       "*not_rendered_dir",
       "rendered_dir/not_rendered_file.ini"
   ]
}

在原始示例中,如果您只是模板化文件夹名称并且不更改 test.py 中的所有内容,那么 cookiecutter.json 应该是:

{
    "project_name": "myproject",

    "_copy_without_render": [
        "test.py"
    ]
}
于 2021-08-31T12:48:03.467 回答