简体   繁体   English

如何从本地文本文件获取内容以在html模板的单独行上打印(Python / Flask)

[英]How to get contents from a local text file to print on individual lines in a html template (Python/Flask)

screenshot of the output I'm looking to get posts from a user to post on individual lines. 输出的截图 ,我希望得到来自用户的帖子张贴在各个行。 At the moment I take in a name, email and comment, pass it to the app.py file and store it to a text file. 目前,我输入一个名称,电子邮件和注释,将其传递到app.py文件并将其存储到文本文件。 I return a name, email, comment and the time of the comment. 我返回姓名,电子邮件,评论和评论时间。 When I read the file and pass in back to the html template the posts display one after the other (see the screenshot included), and im trying to have them display one below each other. 当我阅读文件并将其传递回html模板时,帖子会一个接一个地显示(请参阅随附的屏幕截图),而我试图让它们在彼此之间显示一个。 f.write("\\n") results in the actual text file skipping a line however this does not occur in the template. f.write(“ \\ n”)导致实际的文本文件跳过一行,但是这在模板中不会发生。

form_action.html form_action.html

<html>
<div align = "center">

<body style="background-color: #3DC247;">

<head>
<title>Conor McGregor</title>
</head>
<body>

<div align = "center">
<h1 style="font-family:verdana;">I AM EL CHAPO</h1>
<div align = "center">
<h2 style="font-family:verdana;">YOU'LL DO NUTIN.</h2>

<div align = "center">
<h2 style="font-family:verdana;">Disscusion Page</h2>


 <body>
     <div id="container">
         <div class="title">
            <h3 style="font-family:verdana;">Please fill in your details    
           below and your comment to join the discussion</h3>
        </div>
        <div id="content">
            <form method="post" action="{{ url_for('hello') }}">
              <label for="yourname" style="font-family:verdana;">Please 
           enter your name:</label>
              <input type="text" name="yourname" /><br /><br>

              <label for="youremail" style="font-family:verdana;">Please 
           enter your email:</label>
              <input type="text" name="youremail" /><br /><br>

              <label for="yourcomment"style="font-family:verdana;">Please 
           enter your comment:</label>
              <input type="textarea" name="yourcomment" rows="4" cols="50">               
              <input type="submit" /><br>
            </form>


        </div>  
      </div>
     </div>
    </div>
      <div id="container">
         <div class="title">
            <h1 style="font-family:verdana;"><p>Comments</p></h1>
        </div>
        <div id="content">

                    {{details}}

        </div>  

      </div>
    </body>
  </html>

app.py app.py

 from flask import Flask, render_template, request, url_for
 import time
 import datetime


 # Initialize the Flask application
 app = Flask(__name__)

 # Define a route for the default URL, which loads the form
 @app.route('/')
 def form():
    return render_template('form_submit.html')

 @app.route('/hello/', methods=['POST','GET'])
 def hello():
   global time

   name=request.form['yourname']
   email=request.form['youremail']
   comment=request.form['yourcomment']
   comment_time=time.strftime("%a-%d-%m-%Y %H:%M:%S")

   f = open ("user+comments.txt","a")

   f.write(name + '  ' + email + '   ' + comment + "  " + comment_time)
   f.write('\n')
   f.close()

    with open("user+comments.txt", "r") as f:

    details = f.read()
    f.close()

    return render_template('form_action.html', details = details, name=name,   
    email=email, comment=comment, comment_time=comment_time)


    if __name__ == '__main__':
    app.run(debug=True)

HTML does not know what \\n is. HTML不知道\\n是什么。 You can fix this in two ways. 您可以通过两种方式解决此问题。

  1. Convert str details to list details str详细信息转换为list详细信息

     details = f.read().split('\\n') 

    This converts the str object to list object. 这会将str对象转换为list对象。 You could print it in your template using 您可以使用以下命令将其打印在模板中

     {% for detail in details %} {{detail}} {% endfor %} 
  2. Replace \\n with <br> \\n替换为<br>

     details = f.read().replace('\\n','<br>') 

    and then print it as {{ details|safe }} in form_action.html . 然后在form_action.html其打印为{{ details|safe }} It is important that you use the safe filter . 使用安全过滤器很重要。 The <br> would be escaped without it and rendered as simple text. <br>如果没有它,将被转义并呈现为简单文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM