在 javascript 文件中调用 flask url_for
calling flask url_for in a javascript file
我想从这个 javascript 文件 (header.js) return 到 about.html 页面。我在 javascript 文件中写下了 header。 header.js 将在每个 html 文件中扩展。当我单击一个按钮时,我希望它重定向到 about.html 页面或使用 url_for 的任何其他 html 页面。我只想弄清楚如何从 javascript 文件重定向。 这是我的文件结构
/folder
/index.py
/templates
/index.html
/about.html
/static
/css
/js
/lib
/comp
/header.js
我的header.js
class Header extends HTMLElement {
constructor() {
super();
this.html = `
<header>
<div class="wrapper">
<div id="logo-wrapper">
<img class="logo" src="images/logo3.png" alt="Jebako Logo"/>
<p id='header-name'><a href='index.html'>Jebako</a></p>
</div>
<div id="menu-wrapper">
<p id="menu-icon" class="fas fa-bars"></p>
<ul>
<li><a href="{{ Flask.url_for('about') }}">About</a></li>
<li><a href="media.html">Listen Live <span class="live"></span></a></li>
这是我的 index.py
from flask import Flask, render_template, redirect, request, abort, url_for
app = Flask(__name__)
@app.route('/')
def index_page():
return render_template('index.html')
@app.route('/about/')
def about():
return render_template('about.html')
if __name__ == "__main__":
app.run(debug=True)
您不需要使用 url_for。在index.py变化
app = Flask(__name__)
到
app = Flask(__name__, static_folder='/')
您可以将 html href 链接更改为:
#Or whatever you used app.route() with
href="templates/about"
您还需要更改所有现有链接以使用新的静态文件夹。所以就像 javascript,
<script src = "templates/about.js"></script>