1

I'm coding a website with flask. I'm using flask route only to render html files with the function send_from_directory. The current structure is the followng:

- website
   - app.py
   - views.py
   - static/
       - index.html
       - login.html
       - styles/style.css
       - script/
           - core.js

I cant load the css and js with hyperef from a HTML file by using a route AND a hyperlink. For exemple : i can either load the full login page (content and layout) by clicking the link i put in my index page OR i can load the full page by directly typing in the URL, depending on how i code my page. Is there a way to be able to load the full page no matter how i access it?

this is how i code it to access it by typing the url :<link rel="stylesheet" href="static/styles/style.css">

and this is how i code it to access it throught an hyperlink :<link rel="stylesheet" href="styles/style.css">

Thanks for you time.

I tried this:

from flask import Blueprint, render_template, send_from_directory


views = Blueprint("views", __name__, static_folder="static", template_folder="static")

@views.route("/")
def home():
    return send_from_directory("static", "index.html")


@views.route("/login")
def login():
    return send_from_directory("static", "login.html")
tzsda
  • 19
  • 2

1 Answers1

0

It seems you a pretty new to Flask so i will explain it to you but you should go and read the Flask Documentation.

First the file structure yo have is almost right, you missed the templates folder that Flask uses to identiffy the html/jinja templates.

The way i use to organize my apps:

- project-name/
  - app/
    - static/
      - css/
        - style.css
      - js/
        - my_script.js
    - templates/
      - login.html
      - index.html
    - __init__.py #Here the create_app factory
    - views.py
  - run.py #here i instantied the app: app = create_app()
  - .env # Here sets FLASK_APP env variable to FLASK_APP = "run.py" so flask can detect it

Now that you have a proper templates folder you can use flask render_template() function and url_for() inside your templates, so for example if you need to load css or javasriot into your index.html file you could doit like so:

index.html

<head>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/my_script.js') }}"></script>
</head>

Lastly instead of user send_from_directory funtcion you will be returning:

@views.route("/")
def index():
    return render_template("index.html")