liveBook · Manning

Url_for

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

url_for is a Flask function that constructs a URL from an endpoint and optional parameter values or file paths.

Hardcoded asset paths can become awkward as a Flask application grows. `url_for` builds a URL from a known endpoint instead, so a template can refer to a file without spelling out its full URL path. section 6.4.4

Link a stylesheet

In `base.html`, set a stylesheet link to `href="{{ url_for('static', filename='css/myblog.css') }}"`. Jinja2 evaluates the expression when it renders the template, placing a valid URL in the link. section 6.4.4

The first argument names the endpoint; `filename` supplies the file’s relative path. Putting this link in a shared base template lets child pages inherit the same stylesheet. section 6.4.4

<!DOCTYPE html>
<html>
<head>
                                            {% block head %} #1
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, 
    initial-scale=1, shrink-to-fit=no">
    <title>Your Second Web Server</title>
    {% block styles %}                                       #2
    <link
        rel="stylesheet"
        type="text/css"
        href="{{ url_for('static', filename='css/myblog.css') }}"
     >                                                     #2
    {% endblock %}                                           #2
    {% endblock %}                                           #1
</head>
 
<body>
    <div id="header">
        <h1>MyBlog Home Page</h1>
    </div>
    <div id="content">
        {% block content %}{% endblock %}                    #3
    </div>
    <div id="footer">
        {% block footer %}                                   #4
        <h4>&copy; Copyright 2020 by MyBlog</h4>    
        {% endblock %}    
    </div>
</body>
 
{% block scripts %}{% endblock %}                            #5
 
</html>

The base-template listing shows `url_for` inside the stylesheet link and its surrounding Jinja2 blocks. section 6.4.4

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains endpoint and relative-file arguments through one rendered template expression, without detailing URL-generation internals.
Examples
Shows a `base.html` stylesheet link using `url_for('static', filename='css/myblog.css')`.
What it assumes
Assumes familiarity with HTML links while introducing the Jinja2 expression that calls the Python function.
What you can do after
Apply it via Flask to generate a static-file URL in a Jinja2 template.
How it connects
Connects Flask static files with Jinja2 expression substitution and template inheritance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.