4

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 ?

0

5 Answers 5

2
+100

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') }}">
Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

1

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>

Comments

1

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/

Comments

0

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') }}">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.