Ways to assign a dynamic background image to a div if and only if an image exists in the database

I have been working on implementing dynamic background images for multiple divs in index.html.erb. Currently, I have achieved this by using inline styling with the background URL fetched from my database (using carrierwave). The code snippet looks something like this:

 <div class="style-box col-8 ml-auto mr-auto" style="background: url(<%= place.photos.first.picture.url %>)">
      <h1><%= link_to place.name, place_path(place) %></h1>
      <i><%= place.address %></i>
      <br /><br />
      <p><%= place.description %></p>

The challenge I'm currently facing is that when a new place is created without an image, the view fails to render the complete HTML page due to incomplete data (nil value for place.photos). Is there a way, either using this method or a similar approach, to ensure that the background image only overrides the default style-box background if an image for a new place is present? Normally, I would use an if statement, but I'm struggling to figure out how to use an if statement to update CSS with Rails.

Answer №1

If you prefer to maintain everything in a single line, you can use this approach:

<div class="style-box col-8 ml-auto mr-auto"
    style="background: url(<%= place.photos.first&.picture.url || "/images/default.jpg" %>)">
    <h1><%= link_to place.name, place_path(place) %></h1>
    <i><%= place.address %></i>
    <br /><br />
    <p><%= place.description %></p>
</div>

This code utilizes the or operator (||) to display the first value if available, otherwise defaulting to the second value. Additionally, the & helps prevent errors on the page when no photos are present. Essentially, it is equivalent to:

style="background: url(
    <% if place.photos.first&.picture&.url %>
        <%= place.photos.first&.picture&.url %>
    <% else %>
        /images/default.jpg
    <% end %>
)">

You also have the option of encapsulating this functionality in a helper method for cleaner code, like so:

# Add this to one of the app/helpers modules
def picture_url_or_default(place, default_url = '/images/default.jpg')
    return default_url if place.photos.empty
    return default_url if place.photos.first.picture.nil?
    return default_url if place.photos.first.picture.url.nil?

    place.photos.first.picture.url
end

# Call the helper method in the view
<div class="style-box col-8 ml-auto mr-auto"
    style="background: url(<%= picture_url_or_default(place))">

    ...

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

"Crafting sleek and polished titles using HTML and CSS - A step-by-step guide

I've noticed an increasing number of websites that feature incredibly slick headlines, such as the ones on this site: How do these websites achieve this effect? Are there any subtle hints to look out for? I once heard about a technique involving Fla ...

Preserving proportions in CSS using both width and height measurements

My objective is to set an aspect ratio (for example, 4:3) for a DIV and all its children with the styles WIDTH:100% and HEIGHT:100%. Initially, this method works well by setting the parent's WIDTH:100% and then adding PADDING-BOTTOM: 75%; // (3/4)*1 ...

Tips for positioning a div between two vertically aligned input elements

I'm trying to figure out how to place a div between two inputs with the same height and vertically aligned. It seems like a simple task, but for some reason, the code below isn't working: input{ width: 35%; border: 1px solid #A7A7A7; ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

Implementing a Search Bar with Django and Bootstrap in the Navigation Bar

I recently added a search bar to the navigation menu. My intention was to enable users to input their search query directly into the search bar on the navigation menu and receive results when they hit the search button. However, I encountered an issue wher ...

History.pushState is not a function that I utilize in my work

Can anyone assist me with implementing the history.pushState jQuery code? I am struggling to get it to work and I don't have much knowledge on how to do it. Any help would be greatly appreciated. Here is the code I have so far... <!doctype html> ...

The font implemented in Bootstrap does not appear to be adapting well to different

As I embark on the Bootstrap journey, I find that everything looks great on my desktop browser in terms of responsiveness. However, when I switch to my iPhone 6, it doesn't seem to display as expected... Provided below are a few screenshots: Desktop ...

What is the best approach for resolving the issue of User having an Unknown field(s) (Id_card_number) specified in the system

I'm facing an issue with my code. Whenever I run a makemigrations command, it returns an error message saying Unknown field(s) (Id_card_number) specified for User. How can I resolve this problem? settings.py INSTALLED_APPS = [ 'django.contr ...

I'm attempting to use Bootstrap to align my divs, but unfortunately, it doesn't seem to be working as I had hoped

I've been attempting to align divs using bootstrap, but I'm encountering issues. I prefer not to use a table for this purpose and have experimented with the table tag, but would rather achieve alignment with divs and bootstrap. My familiarity ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

Obtaining <script> and <div> elements from Plotly with Python

Seeking advice on the best way to extract <script> and <div> tags from the HTML output generated by Plotly's offline client. Ideally looking for a built-in method, but open to creating a custom solution if needed. I have experience with B ...

Ways to assign a boolean value to HTML using Angular?

Can someone help me set the initial value of showProduct to false for the app-product HTML selector? showProduct:boolean = false; <button (click)="showProduct=!showProduct">Show Product</button> <div *ngIf="!showProduct"> <app-p ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

Is there a way to format a block of text so that right-to-left text aligns to the right, while left-to-right text aligns

I have a content block that includes text in both left-to-right and right-to-left languages, and I need to ensure that both display correctly. If the user begins with left-to-right text, it should be displayed from left to right with left alignment If the ...

What is the best way to track the loading progress of an AJAX page in WordPress?

On my WordPress blog, I utilize a plugin known as Advanced Ajax Page Loader. This handy tool loads the next page or post through AJAX and then places it in a specific div on my site. However, I am now interested in incorporating a progress bar to show the ...

CSS Float/Clear Challenge (Floating elements conflict)

I divided an image into three parts and aligned them to the right, causing text to wrap around them. Here's a glimpse of the HTML code I used: <img src="" style="float: right;"> <img src="" style="float: right; clear: right;"> <img src ...

Issues encountered with the functionality of the AngularJS greetController Controller

Currently exploring AngularJS, I am following a tutorial and have hit a roadblock trying to get the greetController controller to function properly. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>HTML.it</titl ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Can CSS content be used to showcase an .html document or .html fragment?

Referencing the MDN documentation for css content: /* <uri> value */ content: url(http://www.example.com/test.html); Inquiry: Can an image be displayed using the url() value of the content property in a css html element? .content { conte ...

Transforming CSS Styles of Elements with Bootstrap

After incorporating links and scripts for Bootstrap v4.5 into my project, I quickly noticed that it automatically overrides the styles of text, buttons, and other elements I had previously customized. While I added a Bootstrap alert for authentication pur ...