如何在使用Cookiecutter时省略花括号?

4

我正在用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省略某些花括号?

2
显然,将双大括号添加到模板中的方法是 {{ '{{' }} - 我没有安装cookiecutter来实际测试这个。 - jasonharper
@jasonharper 不确定我理解你的意思? - vdvaxel
1
将该字符串放置在文件应包含“{{”的位置。 - jasonharper
@jasonharper 谢谢,那个方法可行!如果你发表回答,我会采纳它。 - vdvaxel
1个回答

2

从cookiecutter的故障排除文档(或基础的Jinja模板文档)中,为了防止cookiecutter错误解析模板中的大括号{{{

Make sure you escape things properly, like this:

{{ "{{" }}

Or this:

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

See http://jinja.pocoo.org/docs/templates/#escaping for more info.

如果模板是这样的:
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+版本开始提供)。请参考:高级部分 - 不需要渲染的复制

To avoid rendering directories and files of a cookiecutter, the _copy_without_render key can be used in the cookiecutter.json.

{
   "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"
    ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接