【问题标题】:Display files on HTML page as it is在 HTML 页面上按原样显示文件
【发布时间】:2011-08-02 14:50:32
【问题描述】:

我正在为我的项目使用 webpy 框架。我想从我的 webpy 程序中传递一个文件并按原样显示在 html 页面上(文件可以是任何文本文件/程序文件)。我使用 webpy 程序中的以下函数传递了一个文本文件。

class display_files:
    def GET(self):
        wp=web.input()
        file_name=wp.name
        repo_name=wp.repo
        repo_path=os.path.join('repos',repo_name)
        file_path=os.path.join(repo_path,file_name)
        fp=open(file_path,'rU')             #reading file from file path
        text=fp.read()                      #no problem found till this line.
        fp.close()            
        return render.file_display(text) #calling file_display.html 

当我尝试显示来自“file_display.html”的文件(这里是“文本”)时,它会连续显示而不识别换行符。这是我的 html 文件。

$def with(content)
<html>
<head>
    <meta http-equiv="Content-Type" content="text/string;charset=utf-8" >
    <title>File content</title>
</head>
<body>
    <form name="file_content" id="file_content" methode="GET">
        <p> $content</p>
    </form>
</body>
<html>

如何在 html 页面中显示文件。

【问题讨论】:

    标签: python html web.py


    【解决方案1】:

    HTML 将大量空白字符视为单个空白。如果您正在显示的文件包含此文本:

    line one
      line two with indent
    

    呈现的file_display.html 将包含此 HTML:

    <p> line one
      line two with indent</p>
    

    不过,换行符和两个空格将被视为一个空格,在浏览器中会如下所示:

    line one line two with indent
    

    The pre element 告诉浏览器其中的文本已预先格式化,因此应保留换行符和空格。因此,您的模板应如下所示:

    <form name="file_content" id="file_content" methode="GET">
        <pre>$content</pre>
    </form>
    

    至于 Joseph 的建议,web.py 模板系统将为您处理转义。如果您的文件包含&amp;lt;&amp;gt; 等字符,它们将被替换为&amp;lt;&amp;gt;

    【讨论】:

    • 非常感谢 Helgi。你的回答绝对正确。也感谢 Joseph 的回复。
    【解决方案2】:

    看起来您可能需要将任何 全局替换为 <或>分别:

    http://jsfiddle.net/BaULp/

    【讨论】:

    • 我很确定 file_display.html 是一个 web.py 模板文件,而不是 Umni 将要显示的文件。无需转义模板。
    • @Helgi 啊。我不知道 web.py。我只是想找出一种在 pre 标签之间显示 HTML 的方法,因为我认为这是问题所在。 :P 感谢您的信息!
    猜你喜欢
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2013-07-05
    相关资源
    最近更新 更多