Skip to content
Advertisement

How to handle line breaks in a templated file included in a Jinja2 JSON template

I am writing a Jinja2 template to output a JSON DAG where one value is a string containing a list of commands from an external shell script, (containing templated variables. This works if the commands in the script are semicolon-separated on a single line:

JavaScript

But, it fails to render the template when formatted with each command on its own line:

JavaScript

JSONDecodeError: Invalid control character at: line 2 column 29 (char 30)` where character 30 is the line break.

I understand this is because JSON does not support multi-line strings. I am using Jinja2’s {% include path %} to load the file but am not sure how to escape the new lines before rendering them. I was not able to pipe the include output through a Python replace successfully: {% include path | replace("n", " ") %}

I also tried putting the include in a macro with the replace calling inside or outside the macro.

Here is a full example of the template and rendering code.

multi_line.sh

JavaScript

variables.json

JavaScript

template.j2

JavaScript

template_renderer.py

JavaScript

Advertisement

Answer

The solution for me was to wrap the include in a block assignment and then pipe the results into replace to remove occurrences of n.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement