0

I should have 0 displayed on screen until I click on the upload button but I don't. I've minimised the code as much as I could and it still doesn't behave as I would expect it to behave. The if statement is very straightforward, so I must be missing something obvious.

Here is my flask_app.py file:

# Imports
import os

from flask import Flask, render_template, request, session

# Flask Variables
APP = Flask(__name__)


@APP.route('/', methods=["GET", "POST"])
def hello_world():
    messages = ""

    return render_template('upload.html').format(
        messages=messages,
        filename=0,
    )

and here is upload.html file:

<html>
    <head>
        <meta charset="utf-8" />
        <title>Face Transforms</title>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/upload.css') }}">
    </head>
    <body>
        <h1>Face Transforms</h1>

        <form method="POST" action="/" enctype="multipart/form-data">
            <td align="left"><input type="file" name="input_file" /></td>
            <td align="right"><input type="submit" name="submit_button" value="Upload" /></td>
        </form>

        {messages}

        {% if filename == 0 %}
            {filename}
        {% endif %}

    </body>
</html>

I have tried wrapping 0 with "" in the if statement like so {% if filename == "0" %} and with single quotes as well but it still doesn't work.

  • 3
    Did you specifically want to use `.format()` while rendering the template, or could you use: `return render_template('upload.html',messages=messages,filename=0)`? – Patrick Yoder Apr 18 '22 at 14:18
  • 1
    What is the difference between the two? I've tried using `return render_template('upload.html',messages=messages,filename=0)` and it now displays {messages} instead of the content of `messages` – FluidMechanics Potential Flows Apr 18 '22 at 14:19
  • 1
    Yes, you then refer to these variables with double braces like so: `{{messages}}`. The difference is that your jinja if statement should work correctly. – Patrick Yoder Apr 18 '22 at 14:23
  • 1
    This works perfectly except I can't use HTML in my message variable - which I guess is not that big of a deal. I'm a little bit confused as I had been using .format for a year now (but didn't have to deal with any if statements). Why would .format exist if it doesn't let the variables be working in if statements? – FluidMechanics Potential Flows Apr 18 '22 at 14:26
  • Well, the variables work, but not the jinja if statements. To use them, you need to render the templates correctly. To answer your comment on not being able to use HTML, the ['|safe'](https://stackoverflow.com/a/3206446/15368978) filter is available. (`{{ messages|safe }}`) – Patrick Yoder Apr 18 '22 at 14:31

0 Answers0