Search code examples
pythoncookiecutter

How to protect some files from the Jinja template processor?


I am using cookiecutter to create a tornado project, using this template (it has several bugs, so you'll probably won't be able to use it out of the box). I have hit a problem which I do not know how to solve:

jinja2.exceptions.TemplateSyntaxError: unexpected char '\\' at 124272
  File "./{{cookiecutter.project_slug}}/static/swagger/lib/jsoneditor.min.js", line 10

I am not sure, but I have the impression that cookiecutter is trying to Jinja-process the jsoneditor.min.js, which is not supposed to happen, since the "templating" in that file is not supposed to be processed by cookiecutter, it just happens to include the same escape characters that Jinja is using.

Is it possible to tell cookiecutter not to process files inside a certain directory? This is probably a matter of properly setting up the cookiecutter template, but not sure how this can be specified.


Solution

  • By default cookiecutter will try to process every file as a jinja template which produces wrong results if you have something that looks like a jinja template but is only supposed to be taken literal. Starting with cookiecutter 1.1 one can tell cookiecutter to only copy some files without interpreting them as jinja template (documentation).

    To do that you have to add a _copy_without_render key in the cookiecutter config file (cookiecutter.json). It takes a list of Unix shell-style wildcards. If a filename matches any of the patterns, it will be copied and not processed as a jinja template.

    Example

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

    This will not process any javascript files (files which end with .js), any files that are in the not_rendered_dir and not the not_rendered_file.ini in the rendered_dir. They will only get copied.