我想使用 Django 模板引擎来构建一些文本文件:
我写了这个脚本:
from django.template import Template, Context
from django.conf import settings
settings.configure()
with open('etchosts') as fh:
t = Template(fh.read().strip())
c = Context({'hosts': ['host A','host B', 'host C']})
print t.render(c)
模板文件“etchosts”:
=================================
{% for h in hosts %} - {{ h }}
{% endfor %}
=================================
如果我运行我得到的脚本:
=================================
- host A
- host B
- host C
<----- unwanted newline
=================================
如您所见,循环末尾有一个不需要的换行符
如何更改我的模板以具有:
=================================
- host A
- host B
- host C
=================================
?
最佳答案
在 for 循环中时,会出现一个名为 forloop
的额外对象。这包含一些有关循环的信息。请参阅this documentation page .
在您的情况下,代码将如下所示:
=================================
{% for h in hosts %} - {{ h }}{% if not forloop.last %}
{% endif %}{%endfor %}
=================================
问题是,上面的解决方案比您当前的解决方案更清洁吗?就我个人而言,我认为上述解决方案中的额外代码会把事情搞乱,但这只是个人喜好。然而,它是一个有效的替代方案(作为奖励,现在您了解了 forloop 对象)。
关于python - 使用django模板,如何删除循环中最后一项换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23153371/