skip to Main Content

Home.html file:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" type="text/css" href="{{url_for("static",filename="css/css.css")}}">
</head>
<body>
<h1>Welcome to recipe book</h1>
<p>{{length}}</p>
<script>
const amount = {{length}};
console.log(amount);
</script>
</body>

</html>

main.py Flask python file:

#,redirect,url_for,send_from_directory,
from flask import Flask,render_template
import os
app = Flask(__name__)
@app.route("/")
def home():
    parent  = r"C:UserskhaitDesktopWebsiteRecipe_Bookstaticimages"
    everything = os.listdir(parent)
    images = []
    for i in everything:
        if os.path.isfile(os.path.join(parent,i)):
            images.append(os.path.join(parent,i))
    length = len(images)
    return render_template("Home.html",images=images,length=length)

if __name__ == "__main__":
    app.run(debug=True)`

i was just tryna use the length variable in my html. and it throws these errors in relation to this line: "const amount = {{length}};" and this line "console.log(amount);":

Error 1:
Property assignment expected.javascript
Error 2:
Declaration or statement expected.javascript

I am aware many similar questions have been asked on this but i looked through them and couldn’t find an answer to my problem. Any help would be greatly appreciated.

3

Answers


  1. you need to ensure the value is rendered correctly as a js variable. You can use {{ length | tojson }}

    <script>
    const amount = {{ length | tojson }};
    console.log(amount);
    </script>
    
    Login or Signup to reply.
  2. As the above answer states. I can see that you have a syntax error regarding the usage of pipe | and comma ,. try this


    const amount = {{ length | tojson | safe }};


    safe : Will ensure that the content is not auto-escaped by Jinja2.

    <script>
    const amount = {{ length | tojson | safe }};
    console.log(amount);
    </script>
    

    Tell me if you are still facing the error.

    Login or Signup to reply.
  3. I have found 2 issues here.
    The first one being <link rel="stylesheet" type="text/css" href="{{url_for("static",filename="css/css.css")}}">
    There is a syntax issue, instead of using " at all times, try using ' as well because the program will mix them up otherwise. Here is the correct syntax:

    <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='css/css.css')}}">
    

    Second is that try wrapping the {{Length}} in Quotes "{{Length}}" to ensure that the javascript interpreter recieves a a string that represents the numerical value of Length.
    Another method that makes it safer is using tojson but then you might have to adjust some things in your python code:

    <script>
    const amount = {{ length | tojson }};
    console.log(amount);
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search