Utilizing jinja2 to showcase images within a template's CSS

Working on a flask project, I've integrated a visually appealing front-end design from codepen.io into my HTML template using BeautifulSoup. The design can be found here.

I have a list of images obtained through web scraping that I want to display in place of the existing image by utilizing jinja2.

It's worth noting that the images are embedded within the CSS.

.clash-card__image {
  position: relative;
  height: 230px;
  margin-bottom: 35px;
  border-top-left-radius: $border-radius-size;
  border-top-right-radius: $border-radius-size;
}

.clash-card__image--barbarian {
  background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/barbarian-bg.jpg");
  img {
    width: 400px;
    position: absolute;
    top: -65px;
    left: -70px;
  }
}

Although I have successfully displayed images in the body of the HTML template using jinja2, I am facing challenges when it comes to referencing images in the CSS as shown below:

{% for image, title in images_titles %}
.clash-card__image--barbarian {
  background: url("{{images");
 {% endfor %}

Despite attempting various iterations of the above code snippet, I haven't been able to get the images to display. However, I can successfully display the titles since they are located in the HTML part.

An additional hurdle is that the size of the image list may vary. I am seeking a solution where the cards automatically replicate without the need for manually inserting {{image}} references in each CSS definition.

My query is this: How can I effectively incorporate the jinja2 reference to the images stored in the list within the CSS?

Any advice on best practices and suggestions would also be greatly appreciated.

Answer №1

Hopefully, my illustration fulfills your specifications. If you incorporate the background images directly within the element, it can potentially streamline the process for you.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Demo</title>

    <!-- All resources from Clash of Clans Cards -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css" />
    <link rel="stylesheet" href="{{ url_for('static', filename='main.css')}}" />
    <!-- End of resources from Clash of Clans Cards -->

    <style type="text/css">
      .clash-card__image {
        background-color: #1e1e1f;
        background-size: contain; /*cover or contains; determine based on your needs*/
        background-repeat: no-repeat;
        background-position: center center;
      }
    </style>
  </head>
  <body>

    <div class="slide-container">
      {% for image,title in images_titles %}
      <div class="wrapper">
        <div class="clash-card" style="padding-bottom: 3.5rem;">
          <div class="clash-card__image" style="background-image: url({{image}});">
          </div>
          <div class="clash-card__unit-description">
            {{ title }}
          </div>
        </div>
      </div>
      {% endfor %}
    </div>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script>

    <script type="text/javascript">

    (function() {

      var slideContainer = $('.slide-container');

      slideContainer.slick();

      $('.clash-card__image img').hide();
      $('.slick-active').find('.clash-card img').fadeIn(200);

      // On before slide change
      slideContainer.on('beforeChange', function(event, slick, currentSlide, nextSlide) {
        $('.slick-active').find('.clash-card img').fadeOut(1000);
      });

      // On after slide change
      slideContainer.on('afterChange', function(event, slick, currentSlide) {
        $('.slick-active').find('.clash-card img').fadeIn(200);
      });

    })();

    </script>

  </body>
</html>

Answer №2

It seems like you might be attempting to utilize Jinja expressions in a CSS file that is included as a static asset (via a tag such as

<link href='/some/file.css />
).

Unfortunately, this approach will not work since external assets are not processed by Jinja.

An alternative solution could be to include the CSS styles directly in the HTML template within the <head> section like this:

<head>
  <link rel='stylesheet' type='text/css'>
    {% for image, title in images_titles %}
      .clash-card__image--barbarian {
        background: url("{{image}}");
      }
    {% endfor %}
  </link>
</head>

UPDATE:

What is the recommended approach for handling this scenario as it's likely a common requirement?

CSS files are inherently static. In modern setups, these static assets may be served from a CDN or a dedicated folder handled by a reverse proxy like nginx, bypassing the need for WSGI/app server involvement.

Given this context, it appears the current template isn't designed for dynamic image URLs. Upon closer examination, it seems that only the background image is loaded via CSS, while the character image is loaded using an <img> tag. Thus, there are two distinct methods for image loading in this template.

If you need to update the background image, one option would be utilizing Javascript. For example:

var elem = document.getElementsByClassName('clash-card__image--barbarian')[0];
elem.style.backgroundImage = "url('http://localhost:5000/some_image.jpg')"

You might also consider using the fetch API to dynamically retrieve the URL string from an endpoint within your application. However, implementing this would require additional Javascript development beyond the scope of this question.


Without relying on Javascript, if you intend to insert the character image using Jinja2 syntax, you can try something like this:

<div class="clash-card__image clash-card__image--archer">
  <img src="{{image}}" />
</div>

To avoid placing the CSS block in the <head>, you could modify the parent div to incorporate the CSS via a style tag instead:

<div style="background: url('{{bg_image}}');"
  class="clash-card__image clash-card__image--archer">

Subsequently, remove that declaration from the external CSS file. This essentially achieves the same outcome as embedding the CSS within the <head> in the template file, all being rendered by Jinja2 upon page load.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mobile navigation menu options on the left and right sides

I've encountered an issue with my mobile navigation. I have two navigation menus - one on the left and one on the right, designed to slide out when triggered. The left menu functions correctly with a smooth transition, but the right menu abruptly pops ...

Tips for Styling "Opened" Elements within the <Summary><Details> Web Design in HTML using CSS? (a color coding challenge)

I've dedicated a significant amount of time crafting my ultimate HTML FAQ with detailed summaries styled in CSS. There's one aspect that continues to elude me - achieving the perfect orange background color for expanded topics: My goal is for a ...

A div element with a set width that contains an inline child element

I recently created a basic HTML document with two elements: a div with a fixed width, and an image placed after it. According to my understanding, images are inline elements, so I expected the image to appear next to the div on the right side since there ...

Adjust the CSS content using the data-content attribute to include line breaks

My current coding setup includes: <div id="mydiv" data-content="Loading..."></div> This is how I style it with CSS: #mydiv:after{ content: attr(data-content); height: 100%; opacity: 1; position: absolute; text-align: center; ...

Using jQuery to define and apply style attributes

I'm currently working on a script that will add a left and right border to a button in a row of 3 buttons when that specific button is clicked. The goal is for the borders to remain while the button is active, and disappear once another button is clic ...

`Finding Solutions for jQuery and CSS Problems`

My jQuery slideDown/slideUp animation works smoothly in IE9 and Firefox, but is choppy in Chrome. When I remove the css file, the issue disappears, leading me to believe it is a Chrome and CSS interaction problem. Are there any tools available to help ide ...

I'm puzzled as to why my media query for `max-width: 470px` isn't functioning correctly

I'm struggling to get my code to work properly. I've tried adjusting some parts to be more specific and others more general, but it's not functioning as expected. Please review my code and any advice or assistance would be greatly appreciat ...

Tips for stopping the background color from affecting the text color

I'm dealing with a situation where I have an h6 nested inside a div. <div class="cylinder" data-v-5147e140=""> <div data-v-5147e140=""> <h6 class="quantite" data-v-5147e140="&qu ...

Expanding and collapsing multiple rows within a Bootstrap grid

Seeking advice on Bootstrap and its implementation of columns and rows. Currently facing a cascading effect where I have managers, followed by employees, and then employee family members. The challenge lies in my limited understanding of how Bootstrap uti ...

H1 and span elements experiencing abnormal size discrepancies

Check out this code snippet: <h1><a href="">Windows App Store<br /><span class="smallSubText">applications</span></a></h1> and here's the CSS styling: #windowsStoreApplications { float: right; width ...

Chrome's behavior of reducing the width of inline elements when the content is dynamic

Upon opening the specified URL in Google Chrome, an issue can be observed where on the initial load everything appears fine. However, upon refreshing, the width of the three items at the top (Bedingungen, Preise, and So geht's) collapse. This seems to ...

Troubleshooting: Dealing with overflow problem in a span element containing an image tag

One issue I encountered involves overflow. A div is set to overflow: hidden, with all elements inside positioned absolutely. These elements consist of a span tag containing text and an image tag. An arrow allows control of the span tag moving forwards or b ...

A HTML table featuring a stationary header, a scrollbar for horizontal navigation, and columns that adjust in

For the past week, I've been attempting to create an HTML table with a fixed header, dynamic column widths, and horizontal scroll. I've come across several options, but each seems to be lacking in some way. I would greatly appreciate any assista ...

The picture within the bootstrap popover is spilling out of the popover

I need help resolving an issue on my webpage where images in popovers overflow when they reach a certain size. I used an online demo to create the page, but now I'm encountering this problem. How can I fix it? Check out the Js Fiddle for reference: h ...

What is the best way to choose the initial and final <td> that appears within a <tr>?

I am working with an html table that has the following structure: <table> <tbody> <tr> <input type="hidden" name="a" value="x"> <input type="hidden" name="b" value="y"> <td>First Ce ...

Menu button is expanded without the need to click

The Bootstrap 5 button extends the default behavior and does not collapse. Here is the code: <nav id="header-nav" class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class= ...

The text is placed over a beautiful SVG image, adding a decorative touch to

Im interested in incorporating an SVG image of a curly bracket below and between two words, similar to the example shown. https://i.sstatic.net/KuSVg.png Considering the need for responsiveness, I initially attempted adding the image directly into the HT ...

How do I make an image fill the entire space of a div using JQuery and CSS?

html: <body> <div class="custom-div"><input type="button" id="x" name="button" value="Search" onclick="showUser()" class="button"/></div> <input type="image" name="button" value="Search" onclick="showUser()" class="bu ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...

Completely enlarge this inline-block CSS div scan-line

I am looking to create a unique scan line effect that gradually reveals text from left to right, mimicking the appearance of a cathode-ray burning text into a screen's phosphors. The concept involves sliding across black rows with transparent tips. Y ...