简体   繁体   中英

How to render new line from python string to HTML template using FLASK?

message=""
@app.route("/", methods=["GET", "POST"])
def upload_file():
global message
if request.method == "POST":
    if request.files:
        data=request.files["file"]
        if data.filename == "":
            message="File doesn't have a name! <br>"
        elif allowed_file(data.filename):
            message+="File Allowed <br>"
            data.save(os.path.join(app.config["FILE_UPLOAD"], data.filename))
            message+="File Saved"
            if(validate()):
                message+="File validated! <br>"
            else: message+="Failed validation <br>"
        else:
            message+="File extension not allowed! <br>"
return render_template("ui.html",message=message)

I'm trying to validate the file uploaded on my ui.html template using flask and I want to send a "message" string back to ui.html about the status of verification and to show it nicely I'm trying to add new line whenever a new string gets added to "message" string so that when I render it in my ui.html, new line is added where I wanted it to be. This is how I'm rendering the "message" string in ui.html:

{% if message %}
     <p>{{ message }}</p>
{% endif %}

But ui.html is not rendering <br> and it is printing it as a string on ui.html template. How can I resolve this? I have tried <br /> as well.

Also mentioned in render html strings in flask templates flask's template engine (jinja2) assumes that input inside of {{ }} is unsafe and will not allow js or html to be rendered inside of it. The easiest way is to use safe filter in order to do such thing.

{{ message | safe }}

According to flask's documentation https://flask.palletsprojects.com/en/1.1.x/templating/ there are two other ways to control autoescaping behaviour which is either wrap the HTML string in a Markup object or disabling autoescaping altogether like this:

{% autoescape false %}
<p>autoescaping is disabled here
<p>{{ will_not_be_escaped }}
{% endautoescape %}

I tackled it with flash function provided by flask. It prints each message separately so I can add <p> in my HTML File only. The changes made in ui.html file for rendering are:

{% for message in get_flashed_messages() %}
      <p>{{ message }}</p>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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