htmlcssflaskjinja2

Putting a Jinja placeholder in filename for CSS link


(Using Flask , Jinja2, CSS) I want to place a Jinja placeholder into the link to my CSS stylesheets so that I will have a base stylesheet applied to all pages, and unique stylesheets for each page that get passed in through the Flask routes.

What I've tried:

Flask/Python:

return render_template("login.html", style="login.css", form=form)

html/jinja2

<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='{{style}}') }}">

I don't get any errors but the second stylesheet doesn't enact change on the site.


Solution

  • The issue is with how you're nesting the Jinja variable in the second stylesheet link. Try this as an alternative:

    <link rel="stylesheet" href="{{ url_for('static', filename=style) }}">

    You don't need the extra quotes around 'style', Jinja variables already output their contents directly.