Load ‘static’ files (assets)

Notes Single

Static Files

The ‘’url_for()’ function is used to load .css, .js files, images, among others, into the .html document.

.html file:

<!DOCTYPE html>
<html lang="en">

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

<body>
    <img src="{{url_for('static',filename='images/photo.jpg')}}" alt="">

    <h1>My name is {{username}}</h1>
    <p>I am using Flask</p>

    {% if premium %}
    <p>The course is Premium</p>
    {% else %}
    <p>The course is Free</p>
    {% endif %}

    {% if list_of_courses %}
    <p>
        Enjoy our courses:
    </p>
    <ul>
        {%for item in list_of_courses%}
        <li>{{item}}</li>
        {% endfor %}
    </ul>
    {% endif %}
</body>
</html>

The files should be loaded into a directory called 'static' at the root of the project. Within which subdirectories must be created for each of the uses, for example, css files, js files, images, among others.

Archivo css: ‘static/css/style.css’

body {
  background-color: red;
}
img {
  width: 400px;
}

Proceed in the same way with .js files and images.

Links

To navigate through our site through links, you will need to define the routes and use the 'url_for()' function that will take as argument the name of the desired route function.

<a href="{{url_for('about')}}">about</a>
<a href="{{url_for('index')}}">home</a>

In the case of redirects, use:

return redirect(url_for('my_url_objetive'))

Having previously imported 'redirect' and 'url_for':

from flask import Flask, request, redirect, url_for  # Importing Flask

Thanks for reading :)
I invite you to continue reading other entries and visiting us again soon.

Related Posts: