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}}";
let list = {{images | tojson}};
const base_URL = "{{ url_for('static',filename='images') }}"; 
const altText = {0:"Breakfast",1:"Lunch",2:"Dinner",3:"Snacks"};
for(let count=0;count<amount;count++){
    let current_image = document.createElement('img');
    let Cur_URL = base_URL + "/" + list[count];
    console.log(Cur_URL);
    current_image.setAttribute("src",Cur_URL);
    current_image.setAttribute('alt',altText[count]);
    current_image.setAttribute('height','200');
    current_image.setAttribute('width','auto');
    document.body.appendChild(current_image);
}   
</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(i))
    length = len(images)
    return render_template("Home.html",images=images,length=length)

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

I was just trying to 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 and I asked a similar one about the length variable. But that was a numerical flask variable and this is a list flask variable. I looked through them and couldn’t find an answer to my problem. I’m also interested to know what would the proper syntax be for boolean,char and string variables. I assume dict variables would have the same logic as the list variables. Right?
Any help would be greatly appreciated.

2

Answers


  1. the first error is because when you use const amount = "{{length}}"; JavaScript interprets it as declaration but doesn’t recognize the " as a valid JavaScript syntax.
    The second error in referring to the fact that its expecting either a declaration or a statement since {{length}} isn’t recognized as a valid JavaScript expression.

    To correct it you need to remove the " from the {{length}} which directly assigns the value of length to amount and makes it valid for JS. and this works with every format, even JSON.

    Login or Signup to reply.
  2. Try with const amount = Number("{{ length }}");

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search