3

I am trying to print the content of a file in a web page. I want to print each line from the file on a separate line, but instead the line breaks are missing. How do I print the file and preserve newlines?

@app.route('/users')
def print_users():
    v = open("users.txt","r").read().strip()
    # also tried:
    # v = open("users.txt","r").read().strip().split('\n')
    return render_template('web.html', v=v)
{{ v|safe}}
davidism
  • 121,510
  • 29
  • 395
  • 339
chahra
  • 105
  • 1
  • 4
  • 11

2 Answers2

3

You can use :

v = open("users.txt","r").readlines()
v = [line.strip() for line in v]

and then in your html something like (but feel free to play around with it):

<form action="/print_users"  method="post" >    
                    <div class="form-inline">

                  {% for line in v %}
                      <div>{{ line|safe}}</div>
                  {% endfor %}


    <input class="btn btn-primary" type="submit"  value="submit" > 
              </div>

                    </form> 
ml-moron
  • 888
  • 1
  • 11
  • 22
1

While the other answers give great techniques and the current accepted solution works, I needed to do a similar task (rendering a text email template), but needed to extend this to preserve the processing of macros within the file, which led me to create what I think is the simplest and most elegant solution - using render_template_string.

def show_text_template(template_name):
    """
    Render a text template to screen.
    Replace newlines with <br> since rendering a template to html will lose the line breaks
    :param template_name: the text email template to show
    :return: the text email, rendered as a template
    """
    from flask import render_template_string

    txt_template = open(
        '{}/emails/{}{}'.format(app.config.root_path + '/' + app.template_folder, template_name, '.txt'),
        "r").readlines()

    return render_template_string('<br>'.join(txt_template))
Harc
  • 11
  • 2