在HTML页面上显示文件内容
我在我的项目中使用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'显示这个文件(这里是'text')时,它连续显示,没有识别换行符。以下是我的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页面上原样显示这个文件呢?
2 个回答
0
看起来你可能需要把所有的 < 或 > 替换成 < 或 >,这样做是为了让它们在网页上正确显示:
0
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
使用 pre
标签可以告诉浏览器,里面的文本是预格式化的,这样换行和空格就会被保留。因此,你的模板应该是这样的:
<form name="file_content" id="file_content" methode="GET">
<pre>$content</pre>
</form>
至于Joseph的建议,web.py的模板系统会自动处理字符转义。如果你的文件里有像 <
或 >
这样的字符,它们会被替换成 <
和 >
。