Sweety
Sweety

Reputation: 301

Unable to get new lines with "\n" from template to actual output using jinja2

I am trying to generate an xml file with jinja2 module using a template. Somehow I am not able to get new line with \n from template to actual output.

This is xml-template.xml:

<module>
    <group name="abc">
        <subinst entity="x" id="0" />
        {% for n in range(count) %}<subinst entity="y"    id="{{n}}" />\n {% endfor %}
    </group>
</module>

This is my script:

from jinja2 import Template, Environment, FileSystemLoader
count = 3
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader, keep_trailing_newline=True)
template = env.get_template('xml-template.xml')
output = template.render(count=count)
print(output)

When I run my script, I get \n as it is instead of new lines in the output as below.

This is my expected output:

<module>
    <group name="abc">
        <subinst entity="x" id="0" />
        <subinst entity="y" id="0" />
        <subinst entity="y" id="1" />
        <subinst entity="y" id="2" />
    </group>
</module>

I tried using <br> (which is true for HTML), tried using keep_trailing_newline=True but nothing seems to help.

Can someone help me fixing this issue?

Upvotes: 1

Views: 983

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169414

+1 for a very well-written question with example code and expected output.

I got this to work using this template (ensure tabs and spaces are consistent in this file):

<module>
    <group name="abc">
        <subinst entity="x" id="0" />
        {% for n in range(count) %}
        <subinst entity="y" id="{{n}}" />
        {% endfor %}
    </group>
</module>

And this environment (from this answer: https://stackoverflow.com/a/54165000/42346):

env = Environment(loader=file_loader,lstrip_blocks=True,trim_blocks=True)

Example:

In [84]: print(output)
<module>
    <group name="abc">
        <subinst entity="x" id="0" />
        <subinst entity="y" id="0" />
        <subinst entity="y" id="1" />
        <subinst entity="y" id="2" />
    </group>
</module>

Upvotes: 1

Related Questions