Dynamic CSS loading using variable in jinja

Viewed 399

I have a variable UI_BRAND that has the value of blue

I have the following code:

{% if UI_BRAND != 'default' %}
    <link rel="stylesheet" href="{{ url_for('static', filename='UI_BRAND-styles.css') }}">
{% endif %}

I need UI_BRAND-styles.css to evaluate to blue-styles.css. I've tried using {{}} inside if the already existing brackets, but I know that's not allowed.

What would be the best way to dynamically load this CSS file using the value of UI_BRAND ?

5 Answers

How about assigning the filename in the previous line. I thinks it's also easier to read:

{% if UI_BRAND != 'default' %}
  <% set style_filename = UI_BRAND + '-styles.css' %>
  <link rel="stylesheet" href="{{ url_for('static', filename=style_filename) }}">
{% endif %}

or you can use + in the same line with the variable and your string.

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

Correct me if I'm wrong, but this seems to be a good use case for f-strings. Maybe something like this?

filename=f'{UI_BRAND}-styles.css'

The issue with this line:

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

Instead of that you can try this:

{% if UI_BRAND != 'default' %}
    <style src="{{ UI_BRAND }}-styles.css"></style>
{% endif %}

Hope it will solve your issue.


N.B:

You may need to add static root before {{ UI_BRAND }} like this

<style src="static_root/{{ UI_BRAND }}-styles.css"></style>

Don Eitner is close.

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

Concatenation in jinja involves the tilde (~).

So for {"FOO": "a", "BAR": "b", "numbers": "1234" }

FOO ~ BAR

Evaluates to "ab"

And:

{{ numbers | join(BAR ~ FOO ~ "n" ~ FOO ~ "n" ~ FOO) }}

Evaluates to "1banana2banana3banana4"

Here's a useful tool I validated this answer against: https://cryptic-cliffs-32040.herokuapp.com/

CORRECTED and tested. The following results in <link rel="stylesheet" href="/static/blue-styles.css"> in my testing.

<link rel="stylesheet" href="{{ url_for('static', filename='' ~ UI_BRAND ~ '-styles.css') }}">
Related