How to protect some files from the Jinja template processor?
Asked Answered
D

2

14

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.

Diakinesis answered 25/8, 2016 at 6:43 Comment(2)
You probably want to copy without render.Chokeberry
@syntonym: seems to work, thanks! Can you put this as answer, and I'll add a short example, upvote and accept?Diakinesis
C
16

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.

Chokeberry answered 25/8, 2016 at 17:19 Comment(0)
C
7

Just came across this question and also this Github Issue.

It seems like a nice addition, that one can partially mark parts of a file or entire template to not be processed by using the {% raw %} tag:

{% raw %}
{% comment %}Whatever jinja code goes here....{% endcomment %}
...
{% endraw %}
Churchless answered 11/5, 2017 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.