Home.html 文件:
<!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 文件:
#,redirect,url_for,send_from_directory,
from flask import Flask,render_template
import os
app = Flask(__name__)
@app.route("/")
def home():
parent = r"C:\Users\khait\Desktop\Website\Recipe_Book\static\images"
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)`
我只是尝试在我的 html 中使用长度变量。它会抛出与此行相关的错误:“const amount = {{length}};”和这一行“console.log(amount);”:
错误1: 预期属性分配.javascript 错误2: 预期声明或声明.javascript
我知道对此有很多类似的问题,但我浏览了它们,但找不到我的问题的答案。任何帮助将不胜感激。
您需要确保该值正确呈现为 js 变量。您可以使用
{{ length | tojson }}
<script>
const amount = {{ length | tojson }};
console.log(amount);
</script>