简体   繁体   English

Flask + Jinja2脚本导入

[英]Flask + Jinja2 Script imports

I'm having an issue when using Flask and it's templates when importing Scripts and Stylesheets. 使用Flask及其导入脚本和样式表时的模板时出现问题。 I searched everywhere how to do it, and none of them solved my problem. 我到处搜索了如何做,但没有一个解决我的问题。 This is my project's structure: https://i.gyazo.com/f746c58499cbbafa11b023eecb316b15.png This is how I defined Flask's configuration: 这是我项目的结构: https : //i.gyazo.com/f746c58499cbbafa11b023eecb316b15.png这是我定义Flask配置的方式:

app = Flask(__name__,
            template_folder="../web/templates",
            static_folder="../web/static",
            static_url_path=''
)

And this is how i'm importing the scripts : 这就是我导入脚本的方式:

<script src={{ url_for('static', filename='/js/home.js') }}></script>

And this is the msg I get : 这是我得到的味精:

Falló la carga de con fuente “ http://localhost:5000/js/home.js ”. 补充说明“ http:// localhost:5000 / js / home.js ”。

(Basically says that it failed loading that script) (基本上说它无法加载该脚本)

I already read the Quickstart guide from Flask. 我已经阅读了Flask的快速入门指南。 I tried creating a "static" folder in the project's root and not setting anything on the config. 我尝试在项目的根目录中创建一个“静态”文件夹,但未在配置中设置任何内容。 Tried to change the static folder everywhere on my project. 试图在项目的任何地方更改静态文件夹。

Can anyone help me solve this? 谁能帮我解决这个问题? I'm new to Flask and Jinja, but have been searching the whole day and can't make it work. 我是Flask和Jinja的新手,但整天都在搜索,因此无法正常工作。

NOTE : The path for the templates work, my templates work fine, except for .js and .css imports. 注意:模板的路径可以正常工作,我的模板可以正常工作,除了.js和.css导入。

you need to remove starting '/' from <script src={{ url_for('static',filename='/js/home.js') }}. 您需要从<script src={{ url_for('static',filename='/js/home.js') }}.删除以'/'开头<script src={{ url_for('static',filename='/js/home.js') }}.

so change it to <script src={{ url_for('static',filename='js/home.js') }}. 因此将其更改为<script src={{ url_for('static',filename='js/home.js') }}.

your project structure should look like this: 您的项目结构应如下所示:

  • MyFlaskApp/templates/home.html MyFlaskApp /模板/ home.html做为
  • MyFlaskApp/static/js/home.js MyFlaskApp /静态/ JS / home.js
  • MyFlaskApp/app.py MyFlaskApp / app.py

app.py app.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("home.html")


if __name__ == "__main__":
    app.run()

home.html home.html的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src={{ url_for('static',filename='js/home.js') }}> </script>
</body>
</html>

home.js home.js

alert("hello");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM