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
you need to ensure the value is rendered correctly as a js variable. You can use
{{ length | tojson }}
As the above answer states. I can see that you have a syntax error regarding the usage of pipe
|
and comma,
. try thisconst amount = {{ length | tojson | safe }};
safe : Will ensure that the content is not auto-escaped by Jinja2.
Tell me if you are still facing the error.
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: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 ofLength
.Another method that makes it safer is using
tojson
but then you might have to adjust some things in your python code: