无法使用jinja2从模板到实际输出获取带“\n”的新行

2024-10-06 09:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用template生成带有jinja2模块的xml文件。不知何故,我无法从模板到实际输出获得带有\n的新行

这是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>

这是我的剧本:

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)

当我运行脚本时,我得到的是\n,而不是输出中的新行,如下所示

这是我的预期输出:

<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>

我尝试过使用<br>(这对于HTML来说是正确的),尝试过使用keep_trailing_newline=True,但似乎没有任何帮助

有人能帮我解决这个问题吗


Tags: nameidjinja2environmentcountgrouptemplatexml
1条回答
网友
1楼 · 发布于 2024-10-06 09:33:13

对于非常的书面问题+1,带有示例代码和预期输出

我使用此模板实现了这一点(确保此文件中的制表符和空格一致):

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

这个环境(从这个答案:https://stackoverflow.com/a/54165000/42346):

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

例如:

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>

相关问题 更多 >