【问题标题】:Display contents of a text file in Django template在 Django 模板中显示文本文件的内容
【发布时间】:2020-03-30 02:09:48
【问题描述】:

我正在尝试在简单网站中创建一个文件,然后在 Django 视图函数内的变量中读取相同的内容,并将变量解析为要在网页上显示的模板。 但是,当我打印变量时,它在 cmd 上的显示与原始文本文件中的相同,但网页上的输出没有格式,而是显示为单个字符串。

我已经坚持了两天了。

另外我对 django 还比较陌生,并且可以自学

file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):

        file1.write(data.split()[i] + "          ")
        if i%5==0 and i!=0 and i!=5:
        file1.write("\n")
        file1.close()

file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text 
string**
<body>

{% block content %}

        {{dat}}

{% endblock %}

</body>

【问题讨论】:

    标签: python django python-3.x django-templates django-views


    【解决方案1】:

    根据您的需要和要打印的文件格式,您可能还需要查看<pre> HTML tag

    【讨论】:

      【解决方案2】:

      在您的模板中使用linebreaks 过滤器。它会将\n 渲染为&lt;br/&gt;

      像这样使用它: {{ dat | linebreaks }}

      来自文档:

      用适当的 HTML 替换纯文本中的换行符;单 换行变成 HTML 换行符 (&lt;br&gt;) 和一个新行后跟一个 空行变成分节符 (&lt;/p&gt;)。

      如果你不想要&lt;p&gt;标签,你可以使用linebreaksbr

      【讨论】:

      • 谢谢,它成功了。但正如您在我的代码中看到的那样,在网页上显示时,我在它们之间给出的额外空格使其看起来已排序被删除。我尝试搜索过滤器,但它们可以删除空格而不是保留它们
      【解决方案3】:

      这是因为在 HTML 中换行符是 &lt;/br&gt; 在 Python 中是 \n。您应该在渲染之前对其进行转换

      mytext = "<br />".join(mytext.split("\n"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 2013-03-20
        相关资源
        最近更新 更多