seyifunmi
seyifunmi

Reputation: 53

calling flask url_for in a javascript file

I want to return to about.html page from this javascript file (header.js). I wrote my header inside a javascript file. The header.js is going to be extended in every html file. When I click a button I want it to redirect to the about.html page or any other html page using url_for. I just want to figure out how to redirect from a javascript file. This is my file structure

/folder
    /index.py
    /templates
        /index.html
        /about.html
    /static
        /css
        /js
            /lib
            /comp
                /header.js

my 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>

And this is my 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)

Upvotes: 1

Views: 984

Answers (1)

Daniel
Daniel

Reputation: 61

You don't need to use url_for. In the index.py change

app = Flask(__name__)

to

app = Flask(__name__, static_folder='/')

And you can change the html href links to:

#Or whatever you used app.route() with
href="templates/about"

You'll also need to change all existing links to use the new static folder. So like for a javascript,

<script src = "templates/about.js"></script>

Upvotes: 1

Related Questions