disneywithanl
disneywithanl

Reputation: 11

Using a background image in Django using static and variable

I've seen a lot of these types of questions but none are using a {{ variable_name }} in the html using background. For context, I'm trying to insert a unique photo as a background image for every page.The name of the picture associated with every page that is to be inserted onto that page as the background image can be called with {{ item.name }}

<heading id="background-image" style="background-image: url({% static 'img/pattern.jpg' %});">

This will work for a specific background image, "pattern", but I want it to be dependent on a variable for that specific page.

The following code will import the correct image on the page, but it needs to be turned to a background image (so that I may put text in front)

<img src="{% static 'img/' %}{{ item.name }}.jpg" alt="item picture">

So, I'd have to do something like this, in theory, for the background image, but it doesn't work. What are some other ways to introduce a variable in a static manner for the URL field?

<heading id="background-image" style="background-image: url({% static 'img/'}{{ item.name }}'.jpg' %});">

Upvotes: 0

Views: 350

Answers (2)

IVNSTN
IVNSTN

Reputation: 9299

Try like this:

<heading id="background-image" style="background-image: url({% static 'img/' %}{{ item.name }}.jpg);">

static needed to be closed (%}) before {{. You were very close to the solution.

Upvotes: 0

disneywithanl
disneywithanl

Reputation: 11

    <heading id="background-image" style="background-image: url(' {% static 'img/' %}{{ item.name }}.jpg');">

A couple of ticks were in the wrong place. What an annoying, tiny issue I spent days working on!

Upvotes: 1

Related Questions