【问题标题】:calling flask url_for in a javascript file在 javascript 文件中调用烧瓶 url_for
【发布时间】:2021-08-20 20:10:38
【问题描述】:

我想从此 javascript 文件 (header.js) 返回 about.html 页面。我在一个javascript文件中写了我的标题。 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)

【问题讨论】:

    标签: javascript python html flask url-for


    【解决方案1】:

    您不需要使用 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>
    

    【讨论】:

    • 使用 js.file。如果我使用 url_for 我可以使用 '127.0.0.1:5000/aboutpage' 的 url 路径但是当我使用 href='templates/about.html' 时 url 路径是这样的127.0.0.1:5000/about.html
    • 是的,很抱歉。对于在 index.py 中使用 app.route() 定义的页面,请使用您在此处定义的任何方法。因此,例如,您将 about 页面设置为:app.route("/about/") 然后还将 href 更改为 href"/about/" 我还编辑了我的答案以更清晰,希望这可以解决它。跨度>
    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多