pythonhtmlflaskjinja2

Preserve newlines in file rendered to HTML with Jinja


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}}

Solution

  • 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>