我正在用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省略某些花括号?
发布于 2021-08-31 12:48:03
从cookiecutter的Troubleshooting docs (或从底层Jinja Templating docs),以防止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}')另一种选择是,不是转义test.py中的每个{,而是直接告诉cookiecutter跳过整个test.py文件,方法是将其添加到Copy without Render列表(可从cookiecutter 1.1+获得):
为避免呈现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"
]
}https://stackoverflow.com/questions/63469213
复制相似问题