qux
qux

Reputation: 55

Django: how to use {{ something }} inside css file

I have a model called Post with a FileField which is an image.

I want to do something like this:

.article-image{
    background-image: url("../img/{{ post.postimage }});
}

but obviously it does not work, so I tried to make inline css instead:

<div class="article-image" style="background-image:{% static 'img/{{ post.postimage }}' %}"></div>

but it does not work too.

How can I fix this

Upvotes: 1

Views: 76

Answers (1)

Omar Al-Howeiti
Omar Al-Howeiti

Reputation: 1315

for the first case you can't do that because it's CSS file not Django template. but for the second case, you can use template tags like this

create templatetags/my_custom_tag.py in your app and add the following code into it.

from django import template
from your_base_app.settings import STATIC_URL

register = template.Library()

@register.simple_tag
def show_image(img):
    return STATIC_URL + 'img/' + img;

you should load your tags in the top of your django template like that

{% load my_custom_tag %}

your django template should be like this

<div class="article-image" style="background-image:url({% show_image post.postimage.url %})"></div>

Upvotes: 1

Related Questions