1
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.

2 Answers 2

0

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice to know about this, though I tackled it with flash function provided by flask. It prints each message separately so I can add <p> in my HTML File only.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.